gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:11:33 24 4
gpt4 key购买 nike

我要转换加载的图片

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

我想运行一个 PIL filter喜欢 example与变量

TestPicture

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

  • 有没有办法进行这些转换?

  • OpenCV 可以执行 PIL 包中的所有图像过滤器吗?

例子:

enter image description here

结果:

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()

关于python - 将opencv图像格式转换为PIL图像格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com