SoFunction
Updated on 2024-11-13

Detailed explanation of the differences between OpenCV and PIL for reading and displaying images

This blog demonstrates the differences in reading and displaying images using OpenCV and PIL.

First look at the original bgr image

1. Use cv2 to read and convert to rgb format src_rgb.jpg and display and save it

# First read in and save as rgb image
src_path = 'C:\\Users\\Administrator\\Desktop\\cv2_PIL\\' # bgr
img = (src_path)
img = (img, cv2.COLOR_BGR2RGB)
('src_rgb.png', img)
('src_rgb.png', img)
(5000)

2. use cv2 to read src_rgb.jpg and display, found that it is still in rgb format

# Read in rgb format and save the image
src_path = 'C:\\Users\\Administrator\\Desktop\\cv2_PIL\\src_rgb.png' # rgb
img = (src_path)
('src_rgb.png', img)
(5000)

This shows that cv2 reads bgr-format images as bgr-format read-in; it reads rgb-format images as rgb-format read-in.

3. Reading and displaying with PIL

# Use PIL to read bgr format images and display them
src_path = 'C:\\Users\\Administrator\\Desktop\\cv2_PIL\\' # bgr
img = (src_path)#.convert("RGB")
print()
("")

It can be seen that PIL reads bgr format images as rgb format after reading.

4. use PIL to read and turn into numpy array format images and display

# Use PIL to read bgr format images and display them
src_path = 'C:\\Users\\Administrator\\Desktop\\cv2_PIL\\' # bgr
img = (src_path)#.convert("RGB")
print()
img = (img) # rgb
("",img)
(5000)

So further sitting on the fact that PIL reads in bgr format images as being rgb when read in

5. Use PIL to read the rgb format src_rgb.jpg and display it

# Use PIL to read rgb format images and display them
src_path = 'C:\\Users\\Administrator\\Desktop\\cv2_PIL\\src_rgb.png' # rgb
img = (src_path)#.convert("RGB")
print()
# img1 = ()
# print(img1[0,0])
#()
img = (img) # bgr
#print(img)
("src_.png",img)
(5000)

It can be seen that the PIL reads in the rgb order of the image after the RGB format, but in fact the channel order for the BGR format image

Summary:

cv2 reads BGR images img = (''), where img is the image of the BGR channel sequence
cv2 reads RGB images img = (''), where img is the image in RGB channel order
PIL reads in BGR picture img = (''), show img in RGBA format, where img is an image in RGBA channel order; after img = ('RGB'), img is an image in RGBA channel order
PIL reads in RGB images img = ('src_rgb.png'), while displaying img in RGB format, img is an image with channel order in BGR format.

To this point, this article on the OpenCV and PIL to read and display the image of the difference between the article is introduced to this, more related to OpenCV and PIL to read and display the image content, please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!