[Python] Converting Images to Grayscale with Pillow: Explanation of Color Spaces (Color Modes) and Conversion Methods

When converting color images to black and white (grayscale) or to formats suitable for printing, use the convert() method in Pillow.

I will explain the meaning of the “modes (strings)” specified during conversion and the code to actually convert images to grayscale.

目次

Main Color Spaces (Color Modes) in Pillow

The following are the main mode identifiers used when loading images with Image.open() or converting them with convert().RGB vs CMYK vs Grayscale color modelsの画像

Mode StringType of Color SpaceDescription
LGrayscaleAn 8-bit (0-255) black and white image. 0 represents black, and 255 represents white.
RGBTrue ColorThe most common color format for PCs, expressing color with 3 channels (Red, Green, Blue), each 8 bits.
CMYKPrint ColorA format for printing expressed with 4 channels: Cyan, Magenta, Yellow, and Key plate (Black).
1Bilevel ImageA purely black and white image with 1 bit (0 or 1). There are no intermediate gray colors.
RGBATransparent ColorA format that adds Transparency (Alpha) to RGB. Used in PNGs, etc.

Executable Sample Code

The following code is a script that loads a color image, converts it to grayscale (L mode), and saves it.

from PIL import Image, ImageDraw
import os

def convert_to_grayscale():
    input_filename = "vivid_landscape.jpg"
    output_filename = "monochrome_landscape.jpg"
    
    # Create a color image for operation verification (if file doesn't exist)
    if not os.path.exists(input_filename):
        create_test_color_image(input_filename)

    try:
        # 1. Load image
        with Image.open(input_filename) as img:
            print(f"Original Mode: {img.mode}")  # Usually 'RGB'

            # 2. Convert to Grayscale
            # Just calling convert("L") generates a natural black and white image based on luminance
            gray_img = img.convert("L")
            
            print(f"Converted Mode: {gray_img.mode}") # Confirm it changed to 'L'

            # 3. Save
            gray_img.save(output_filename)
            print(f"Saved: {output_filename}")

            # Reference: If you want to binarize (black or white only), specify "1"
            # binary_img = img.convert("1")
            # binary_img.save("binary_sample.jpg")

    except Exception as e:
        print(f"An error occurred: {e}")

def create_test_color_image(filename):
    """Create a colorful image for verification"""
    width, height = 400, 300
    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)
    
    # Draw Red, Green, and Blue strips
    draw.rectangle((0, 0, width//3, height), fill="red")
    draw.rectangle((width//3, 0, width*2//3, height), fill="green")
    draw.rectangle((width*2//3, 0, width, height), fill="blue")
    
    img.save(filename)
    print(f">> Created test image: {filename}")

if __name__ == "__main__":
    convert_to_grayscale()

Explanation: Importance of the convert Method

image.convert(mode) does not just change the colors; it modifies the internal representation of the pixel data itself.

  • File Size Reduction: Converting from RGB (24 bits per pixel) to L (8 bits per pixel) reduces the amount of information in the image, allowing for smaller file sizes when saving.
  • Preprocessing for Image Processing: Before performing image analysis such as OCR (Optical Character Recognition) or edge detection, it is common to convert images to grayscale to reduce noise and computational load.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次