-1

I have 1000 of images. Now I like to convert those images into grayscale?

import tensorflow as tf
from tensorflow.keras.utils import img_to_array
#df['image_name'] = df['image_name'].apply(str)
df_image = []
for i in tqdm(range(df.shape[0])):
    img = image.load_img('/content/drive/MyDrive/Predict DF from Image of Chemical 
    Structure/2D image/'+df['image_name'][i]+'.png',target_size=(100,100,3))
    img = image.img_to_array(img)
    img = img/255
    df_image.append(img)
X = np.array(df_image)
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Pranab
  • 379
  • 3
  • 11
  • 2
    Are you looking for code or the concept. You can refer to solutions @ https://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python – Pavan Kumar Polavarapu Jan 29 '23 at 06:27

1 Answers1

2

Per the TensorFlow documentation for tf.keras.utils.load_img, it accepts the argument color_mode, which is

One of "grayscale", "rgb", "rgba". Default: "rgb". The desired image format.

and it also returns "A PIL Image instance.".

The best way to do this is

img = image.load_img(
    '/content/drive/MyDrive/Predict DF from Image of Chemical Structure/2D image/'+df['image_name'][i]+'.png',
    target_size=(100,100,3),
    color_mode="grayscale"
)

If I'm misinterpreting the documentation, the following should also work (put this after load_img but before img_to_array):

img = img.convert("L") # if you need alpha preserved, "LA"

Since this is a PIL Image instance, it has the .convert method. "L" converts the image to just lightness values

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34