区分PIL和CV2图像

发布于 2025-01-26 04:48:48 字数 231 浏览 3 评论 0原文

我希望使用TF模型,但是图像预处理需要PIL图像。我希望我的程序能够同时接受PIL和CV2图像。我知道如何将CV2图像转换为PIL图像,但是我不知道如何区分它们以知道何时应用转换。 因此,我需要一个类似的条件:

if image is PIL.Image:
    ...
elif image is CV2.Image:
   conversion
   ...

有人有一种方法吗?

I am looking to use a TF model, but the image preprocessing requires PIL images. I want my program to be able to accept both PIL and CV2 images. I know how to convert a CV2 image to a PIL image, but I don't know how to differentiate between them to know when to apply the conversion.
So I need a condition like :

if image is PIL.Image:
    ...
elif image is CV2.Image:
   conversion
   ...

Does anyone have a method for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

入画浅相思 2025-02-02 04:48:48

当您使用cv2打开图像时,它将返回类型numpy.ndarray的对象,但pil的image.open()返回pil .jpegimageplugin.jpegimagefile。因此,使用此方法,您基本上可以区分在情况下使用的(假设不涉及将一种图像类型转换为另一种图像类型的转换或进一步处理)。

import cv2
from PIL import Image
from PIL import JpegImagePlugin

imgcv = cv2.imread('./koala.jpg')
print(type(imgcv))

imgpil = Image.open('./koala.jpg')
print(type(imgpil))

img = imgpil
if isinstance(img,JpegImagePlugin.JpegImageFile):
    print('PIL Image')
else:
    print('Not PIL')

输出:

<class 'numpy.ndarray'>
<class 'PIL.JpegImagePlugin.JpegImageFile'>
PIL Image

如本答案的评论(由Mark Setchell)所述,我们还可以检查ndarray ndarray 检查,然后决定 - 既然是pil''班级可能会在将来发生变化,否则它们可能只是使用不同的类型。支票将完全相同。

img = imgcv
if isinstance(img,numpy.ndarray):
    print('CV Image')
else:
    print('PIL Image')

When you open an image using CV2 then it returns object of the type numpy.ndarray but PIL's Image.open() returns PIL.JpegImagePlugin.JpegImageFile. So using that, you can basically differentiate which is used in your case (assuming there is no conversion or further processing involved which converted one image type to another).

import cv2
from PIL import Image
from PIL import JpegImagePlugin

imgcv = cv2.imread('./koala.jpg')
print(type(imgcv))

imgpil = Image.open('./koala.jpg')
print(type(imgpil))

img = imgpil
if isinstance(img,JpegImagePlugin.JpegImageFile):
    print('PIL Image')
else:
    print('Not PIL')

Output:

<class 'numpy.ndarray'>
<class 'PIL.JpegImagePlugin.JpegImageFile'>
PIL Image

As mentioned in the comment of this answer (by Mark Setchell) that instead of changing the PIL's JpegImageFile class, we can also check ndarray check and then decide - since PIL's class might change in future or they may simply use different type. The check would be exactly the same though.

img = imgcv
if isinstance(img,numpy.ndarray):
    print('CV Image')
else:
    print('PIL Image')
橘寄 2025-02-02 04:48:48

不要试图区分。读取后立即转换图像对象,以便您的程序始终处理一致的图像类型。

Don't try to differentiate. Just convert the image object immediately after reading it so that your program is always dealing with a consistent image type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文