Search code examples
pythonpython-imaging-libraryrgbfile-handlinggrayscale

Python script to convert RBG image dataset into Grayscale images using pillow


I want to convert an image RGB dataset to Grayscale dataset using pillow. I want to write a script that takes in the dataset path and converts all images one by one into grayscale. At the end I want to save this script, and want to run this script on the server to avoid the copying of huge data to the server.


Solution

  • Probably this code would work for you?

    Code:

    import os
    from PIL import Image
    dir = '/content/pizza_steak/test/pizza'
    for i in range(len(os.listdir(dir))):
        # directory where images are stored
        dir = '/content/pizza_steak/test/steak'
    
        # get the file name
        file_name = os.listdir(dir)[i]
    
        # creating a final path
        final_path = dir + '/' + file_name
    
        # convet and save the image
        Image.open(final_path).convert('L').save(f"/content/meow/gray{file_name}")
    
        # uncomment this is you want to delete the file
        # os.remove(final_path)