将opencv图像格式转换为PIL图像格式?

Convert opencv image format to PIL image format?

我要转换加载的图片

TestPicture = cv2.imread("flowers.jpg")

我想运行一个PIL filter like on the example和变量

TestPicture

但我无法在这些类型之间来回转换它。

示例:

结果:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold_img = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
im_pil = cv2_to_pil(threshold_img)
pytesseract.image_to_string(im_pil)
Out[5]: 'TUM'

是的,OpenCV 更健壮、更灵活,可以执行大多数可用的图像处理例程,所以这个过滤器可能可以用 OpenCV 完成>但是,可能没有直接的 API为了那个原因。

无论如何,就图像格式从 OpenCV 到 PIL 的转换而言,您可以使用 Image.fromarray 作为:

import cv2
import numpy as np
from PIL import Image

img = cv2.imread("path/to/img.png")

# You may need to convert the color.
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(img)

# For reversing the operation:
im_np = np.asarray(im_pil)

但是你必须记住,OpenCV 遵循 BGR 约定,PIL 遵循 RGB 颜色约定,所以为了保持一致,你可能需要使用 cv2.cvtColor() 转换前。

PillowOpenCV 使用不同格式的图像。所以你不能只读取 Pillow 中的图像并将其处理成 OpenCV 图像。 Pillow 使用 RGB 格式作为 @ZdaR 突出显示,并且 OpenCV 使用 BGR 格式。因此,您需要一个转换器来将一种格式转换为另一种格式。

要从 PIL 图像转换为 OpenCV 使用:

import cv2
import numpy as np
from PIL import Image

pil_image=Image.open("demo2.jpg") # open image using PIL

# use numpy to convert the pil_image into a numpy array
numpy_image=numpy.array(pil_img)  

# convert to a openCV2 image, notice the COLOR_RGB2BGR which means that 
# the color is converted from RGB to BGR format
opencv_image=cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR) 

要从 OpenCV 图像转换为 PIL 图像,请使用:

import cv2
import numpy as np
from PIL import Image

opencv_image=cv2.imread("demo2.jpg") # open image using openCV2

# convert from openCV2 to PIL. Notice the COLOR_BGR2RGB which means that 
# the color is converted from BGR to RGB
color_coverted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)
pil_image=Image.fromarray(color_coverted)

这里有两个函数可以在 PIL 和 OpenCV 之间转换图像:

def toImgOpenCV(imgPIL): # Conver imgPIL to imgOpenCV
    i = np.array(imgPIL) # After mapping from PIL to numpy : [R,G,B,A]
                         # numpy Image Channel system: [B,G,R,A]
    red = i[:,:,0].copy(); i[:,:,0] = i[:,:,2].copy(); i[:,:,2] = red;
    return i; 

def toImgPIL(imgOpenCV): return Image.fromarray(cv2.cvtColor(imgOpenCV, cv2.COLOR_BGR2RGB));

从 OpenCV img 转换为 PIL img 将丢失透明通道。虽然将 PIL img 转换为 OpenCV img 将能够保持透明通道,但 cv2.imshow 虽然不显示它但另存为 png 会正常给出结果。