The difference and connection between python cv2.imread() and Image.open()


Insert image description here

1. cv2.imread()

The data format read by cv2.imread() is numpy, and it is read according to flag=1 by default.

example:

import cv2

img = cv2.imread("img_path")
print(img.shape, type(img))

# 显示图像
cv2.imshow("demo", img)

# 窗口显示时间,默认0表示无限
cv2.waitKey()

# 按任意键销毁窗口
cv2.destoryWindows("demo")

>>>输出345,678,3<class.'numpy.ndarray'>

1.1 cv2.imread parameter description

flags: How to read images, optional
① cv2.IMREAD_COLOR(1): Default mode, 3-channel BGR color image
② cv2.IMREAD_GRAYSCALE(0): Single-channel grayscale image
③ cv2.IMREAD_UNCHANGED(-1): Return as is (using Alpha channel)
④ cv2.IMREAD_ANYDEPTH (2): Returns a 16-bit/32-bit image when the input has the corresponding depth, otherwise it is converted to 8-bit
⑤ cv2.IMREAD_ANYCOLOR(4): Read in any possible color format

Return value: read OpenCV image, nparray multidimensional array

1.2 Precautions

⑴ Color images in OpenCV use BGR format, while PIL, PyQt, matplotlib and other libraries use RGB format.

import cv2

# 方法1:BGR 转 RGB
img = img[:, :, ::-1]

# 方法2:BGR 转 RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

⑵ If cv2.imread() cannot read the image from the specified file, it will not report an error, but return an empty matrix.

⑶ In python3, the path and file name of the image are not supported in Chinese or have spaces. When Chinese must be used, cv2.imdecode() can be used to process it.
Example:

import cv2

imgFile = './images/测试.jpg'

# cv2.imread(imgFile)  读取失败但不会报错

img = cv2.imdecode(np.fromfile(imgFile, dtype=np.uint8), -1)

⑷ When reading an image, the transparent channel is ignored by default, but the transparent channel can be read using the CV_LOAD_IMAGE_UNCHANGED parameter.

2. Image.open()

Image.open() return value is in PIL type format, which can directly display the image, but cannot directly read the pixel values.
Example:

from PIL import Image

img = Image.open('./image9.jpg')
print(img, img.size)
img.show()

>>>输出
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1920x1080 at 0x222AD1D4160> (1920, 1080)


3. Mutual conversion between cv2.imread() and Image.open()

3.1 cv2.imread() is converted to Image.open(): Image.fromarray()

import cv2
from PIL import Image

img_cv2 = cv2.imread('img_path')

# 方法1
img_cv2 = img_cv2[:, :, ::-1]

# 方法2 
img_cv2 = cv2.cvtColor(img_cv2, cv2.COLOR_BGR2RGB)

img_PIL = Image.fromarray(img_cv2)

3.2 Image.open() converted to cv2.imread(): np.array()

example:

import cv2
from PIL import Image
import numpy as np

img_PIL = Image.open('img_path')

# 方法1
img_PIL = img_PIL[:, :, ::-1]

# 方法2
img_PIL = cv2.cvtColor(img_PIL, cv2.COLOR_RGB2BGR)

img_cv2 = np.array(img_PIL)

Summary: The data format read by cv2.imread() is numpy, and the return value of Image.open() is PIL type format.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_41273999/article/details/134569426