1. 程式人生 > >matplotlib.pyplot與cv2、Image.open 讀取圖片顯示的差異

matplotlib.pyplot與cv2、Image.open 讀取圖片顯示的差異

簡介

In the Python bindings of OpenCV, images are represented as NumPy arrays in BGR order. This works fine when using the cv2.imshow function. However, if you intend on using Matplotlib, the plt.imshow function assumes the image is in RGB order. A simple call to cv2.cvtColor will resolve this problem, or you can use the opencv2matplotlib convenience function.

cv2.imshow讀取圖片的NumPy arrays陣列是以 BGR order形式儲存的,而Matplotlib中的plt.imshow 是以RGB順序儲存的。若要以plt顯示需要用imutils.opencv2matplotlib函式,或者要將Image.open 讀取的圖片正常顯示需要cv2.cvtColor來呼叫。

程式碼

import matplotlib.pyplot  as plt
import cv2
import imutils


cactus = cv2.imread('')  
# INCORRECT: show the image without converting color spaces
plt.figure("Incorrect") plt.imshow(cactus) # CORRECT: convert color spaces before using plt.imshow plt.figure("Correct") plt.imshow(imutils.opencv2matplotlib(cactus)) plt.show()

效果

這裡寫圖片描述

參考