0

I'm working on face recognition app and prepared dataset that reads jpg images and then trains my neural network. In order to improve accuracy I decided to convert my images to grayscale (inside mapping function). Here is the way how I convert image to a tensor:

from PIL import Image

image_data = tf.io.decode_jpeg(
  image_bytes_string,
  channels=3
)

image_data = tf.reshape(image_data , (277, 370, 3))

label = parsed['label']
label = tf.reshape(label, (1,))

return image_data, label

The code how I display image:

image_data = dataset_item[0].numpy()
img = Image.fromarray(image_data)
img

After changing code to convert to a grayscale the code that shows image displays this error:

KeyError: ((1, 1, 1), '|u1')
During handling of the above exception, another exception occurred:
Cannot handle this data type

Grayscale code:

image_data = tf.io.decode_jpeg(
  image_bytes_string,
  channels=3
)

grayscale = tf.image.rgb_to_grayscale(
  image_data
)

image_data = tf.reshape(grayscale, (277, 370, 1))

label = parsed['label']
label = tf.reshape(label, (1,))

return image_data, label

Is there problem with how I convert my image to a grayscale or a problem with PIL library?

UPD: Here is the colab with an example: https://colab.research.google.com/drive/1v72_C5i8HZzSLEy_p6d45EWq1byoF3fe

Alex Zaitsev
  • 2,544
  • 5
  • 18
  • 27

1 Answers1

0

I really stuck in same error but the following code may help you to display gray_scale image.

In below code you can see metrics [...,0] is known as Ellipsis_object.

grey_img = tf.image.rgb_to_grayscale(jpeg_image)
_ = plt.imshow(grey_img[...,0], cmap='gray')
  • Welcome to stack overflow! Please add images directly to the answer, since links can become invalid. And while this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. [Reference](https://meta.stackoverflow.com/questions/300837/what-comment-should-i-add-to-code-only-answers) – Kim Tang Oct 20 '20 at 10:35