区分PIL和CV2图像
我希望使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用
cv2
打开图像时,它将返回类型numpy.ndarray
的对象,但pil的image.open()
返回pil .jpegimageplugin.jpegimagefile
。因此,使用此方法,您基本上可以区分在情况下使用的(假设不涉及将一种图像类型转换为另一种图像类型的转换或进一步处理)。输出:
如本答案的评论(由Mark Setchell)所述,我们还可以检查
ndarray
ndarray 检查,然后决定 - 既然是pil''班级可能会在将来发生变化,否则它们可能只是使用不同的类型。支票将完全相同。When you open an image using
CV2
then it returns object of the typenumpy.ndarray
but PIL'sImage.open()
returnsPIL.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).Output:
As mentioned in the comment of this answer (by Mark Setchell) that instead of changing the PIL's
JpegImageFile
class, we can also checkndarray
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.不要试图区分。读取后立即转换图像对象,以便您的程序始终处理一致的图像类型。
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.