Matplotlab display the image read by OpenCV
1. Confirm the number of array of images
Using OpenCV()
When the function reads the image, the second parameter (logo) determines the way of reading the image. Specifically,0
、1
and-1
Corresponding to different reading modes:
Read mode | Signs | value |
---|---|---|
Gray | cv2.IMREAD_GRAYSCALE |
0 |
Color (ignore transparency channel) | cv2.IMREAD_COLOR |
1 |
Color (including alpha transparency channel, if existence) | cv2.IMREAD_UNCHANGED |
-1 |
Do not discuss the image containing transparent channels here
useJudgment image type
In OpenCV, when you use it()
When a function reads a image, it will load the image to the memory and store it as a Numpy array.It is a attribute of the Numpy array, which returns a tuple containing the size of each dimension of the array. By checking the length of the tuple (that is, the number of dimensions), we can determine the type or structure of the array.
-
Gray image: Usually a two -dimensional array, indicated as
(height, width)
,The return length of the return is 2.
-
Color image: Usually a three -dimensional array, indicated as
(height, width, channels)
,channels
Indicates the number of color channels (for example, there are three channels for RGB images, and the shape is usually(height, width, 3)
),The length of the return tuple is 3.
# IMG is a Numpy array
if len () == 2:
Print ("This is a gray image"))
elif len () == 3:
Print ("This is a color image"))
2. Use Matplotlab to display
Gray image
(img, cmap='gray')
understandcmap='gray'
directimshow
Will use the default color mapping (usuallyviridis
), This is usually not the ash effect that is expected. It is necessary to clearly specify the color mapping (CMAP) to 'Gray' so that each pixel value in the image can be correctly mapped to the gray level.
Color image
The color channel sequence of OpenCV reads is the order of color channelsBGR
, Matplotlib reads the displayed color channel asRGB
, So you need to read the channel when you read
(img[:, :, ::-1])
understandimg[:, :, ::-1]
The first -dimensional and second -dimensional represents the height and width of the image. There are three channels for the third dimension: red (R), green (g), and blue (b)
-
:
See all elements. -
::-1
It is the slice syntax in Python, which indicates that the element is selected from the end (reverse order). The intention here is usually the data of the last dimension, such as converting the RGB format into a BGR format, or the opposite.
Copyright © 2025 Log All rights reserved.