Home > database >  How to prepare PIL Image.Image for tf.image.decode_image
How to prepare PIL Image.Image for tf.image.decode_image

Time:01-21

For a file read with:

import PIL
import tensorflow as tf
from keras_preprocessing.image import array_to_img

path_image = "path/cat_960_720.jpg"

read_image = PIL.Image.open(path_image)
# read_image.show()

image_decode = tf.image.decode_image(read_image)
print("This is the size of the Sample image:", image_decode.shape, "\n")
print("This is the array for Sample image:", image_decode)

resize_image = tf.image.resize(image_decode, (32, 32))
print("This is the Shape of resized image", resize_image.shape)
print("This is the array for resize image:", resize_image)

to_img = array_to_img(resize_image)
to_img.show()

I keep getting error for this line tf.image.decode_image(read_image):

ValueError: Attempt to convert a value (<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=960x586 at 0x11AA49F40>) with an unsupported type (<class 'PIL.JpegImagePlugin.JpegImageFile'>) to a Tensor.

How can I pass imae read with PIL to tensorflow so that I could decode and resize, so that I could resize this big picture to 32x32x3?

CodePudding user response:

A few options, here is 1 if you have to use PIL:

import PIL
import tensorflow as tf
from keras_preprocessing.image import array_to_img
import numpy as np

path_image = "/content/cat.jpg"

read_image = np.asarray(PIL.Image.open(path_image))
resize_image = tf.image.resize(read_image, (32, 32))
print("This is the Shape of resized image", resize_image.shape)
print("This is the array for resize image:", resize_image)

to_img = array_to_img(resize_image)

Here is an option with TF only:

import tensorflow as tf
from keras_preprocessing.image import array_to_img

path_image = "/content/cat.jpg"

read_image = tf.io.read_file(path_image)
read_image = tf.image.decode_image(read_image)
resize_image = tf.image.resize(read_image, (32, 32))
print("This is the Shape of resized image", resize_image.shape)
print("This is the array for resize image:", resize_image)

to_img = array_to_img(resize_image)
  • Related