Home > Back-end >  How can i convert images into grayscale?
How can i convert images into grayscale?

Time:01-29

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)

CodePudding user response:

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

  • Related