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?
CodePudding user response:
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')
CodePudding user response:
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.