Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

write a python script that takes all images in a folder and makes them black and white

  1. User

    write a python script that takes all images in a folder and makes them black and white

  2. Assistant

    You can use the Python Imaging Library (PIL) to convert images to black and white. Here's a script that takes all the images in a folder and converts them to black and white:

    from PIL import Image
    import os
    
    def convert_to_bw(image_path, save_path):
        image = Image.open(image_path).convert("L")
        image.save(save_path)
    
    def batch_convert_folder(input_folder, output_folder):
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
    
        for filename in os.listdir(input_folder):
            if filename.endswith(".jpg") or filename.endswith(".png"):
                image_path = os.path.join(input_folder, filename)
                save_path = os.path.join(output_folder, filename)
                convert_to_bw(image_path, save_path)
                print(f"Converted {image_path} to black and white.")
    
    input_folder = "path/to/input/folder"
    output_folder = "path/to/output/folder"
    
    batch_convert_folder(input_folder, output_folder)
    

    Make sure to replace "path/to/input/folder" and "path/to/output/folder" with the actual paths to your input and output folders. This script converts all the .jpg and .png images in the input folder to black and white images, and saves them in the output folder.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.