简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM