OpenCV and PIL image object conversion

OpenCV and PIL (Python Imaging Library) are both commonly used Python image processing libraries. They each have their own image object type, so you need to convert accordingly when using them.

The following is the conversion method between OpenCV image object and PIL image object:

  1. Convert OpenCV image object to PIL image object:
import cv2
from PIL import Image

# 读取OpenCV图像对象
img_cv = cv2.imread('image.jpg')

# 将OpenCV图像对象转换为PIL图像对象
img_pil = Image.fromarray(cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB))
  1. Convert PIL image object to OpenCV image object:
import cv2
from PIL import Image

# 读取PIL图像对象
img_pil = Image.open('image.jpg')

# 将PIL图像对象转换为OpenCV图像对象
img_cv = cv2.cvtColor(numpy.array(img_pil), cv2.COLOR_RGB2BGR)

It should be noted that OpenCV and PIL process images differently, so you need to pay attention to the channel order and color space conversion of the image when converting.

Guess you like

Origin blog.csdn.net/qq_41704436/article/details/132187482