opencv and matplot display pictures

Here is a picture, the picture name is flower.jpg Insert image description here
During image processing, if we need to display the picture, we can use opencv to read and display it, or we can use matplotlib to read and display it. However, the way opencv reads color images is not RGB. Opencv reads it in the form of BGR by default (the historical reason for this seems to be related to the camera, you can check the relevant information).

Read pictures

The following is how opencv and matplotlib read images

import cv2 as cv
import matplotlib.pyplot as plt
#opencv
imgA = cv.imread("flower.jpg",1)
# matplotlib
imgB = plt.imread("flower.jpg")

Show pictures

Using the same module to read and display, the effect is the same. The difference mentioned here is mainly the storage method of imgA and imgB.

opencv

Insert image description here

matplotlib

Insert image description here

Display using different modules

opencv reads, matplot displays.
Insert image description here

Compared

imgA stored by opencv:
Insert image description here
imgB stored by matplotlib:
Insert image description here
It can be seen that imgA and imgB are both three-dimensional matrices. The three innermost elements are what we often call "RGB", while opencv and matplotlib do the opposite, using BGR.

Display images using matplitlib

If we want to convert opencv images to RGB format and display them, we can refer to the following methods.

Channel splitting and remerging

import cv2 as cv
import matplotlib.pyplot as plt
	
img = cv.imread("flower.jpg", 1)
b, g, r = cv.split(img)    #通道分离
img = cv.merge([r, g, b])    #改序合并
plt.imshow(img)
plt.show()

The result is as shown below:

Insert image description here

Using the cvtColor function

import cv2 as cv
import matplotlib.pyplot as plt
	
img = cv.imread("flower.jpg", 1)
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)  #颜色通道转换
plt.imshow(img)
plt.show()

The result is as shown below:
Insert image description here

Reverse slice access

Numpy arrays can also be accessed using slices, and img is also a numpy array.

import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread("flower.jpg", 1)
img = img[:,:,::-1]    #色彩是第三个维度,::-1 表示矩阵的逆序全访问
plt.imshow(img)
plt.show()

Insert image description here

Guess you like

Origin blog.csdn.net/m0_67313306/article/details/127524254