[PYTHON] [Caution] When creating a binary image (1bit / pixel), be aware of the file format!

Introduction

Hello! This time I would like to talk about the file format when creating a binary image.

Here, the case of "converting a grayscale image (8bits / pixel) to a binary image (1bit / pixel)" will be explained as an example.

The explanation is based on image conversion using pillow, but this story is due to the file format, so you should definitely know it when creating a binary image (1bit / pixel). is.

On the other hand, if you want to save the binary image as 0 (black) and 255 (white), it will be 8 bits / pixel, so the format explained here does not meet your expectations. (Change the extension to JPEG, etc. and save.)

What file format can save a binary image (1bit / pixel)?

It is a binary image drawn in black and white, but it is common to set 1 pixel (1 pixel) to 1 bit (0: black, 1: white).

However, depending on the file format, 1 pixel (1 pixel) cannot be saved in 1 bit (0: black, 1: white) like grayscale, and it may be saved in 8 bits (0: black, 255: white). To do. (JPEG is applicable.)

Therefore, if you want to save 1 pixel as 1 bit (0: black, 1: white), you need to select a compatible file format. The following are typical examples. png pbm bmp etc

Since pillow is used in this example, check if the file format is supported by pillow. https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html

You can see that png and bmp are compatible with pillow.

I will not use it this time, but if you want to use another library such as openCV, please check again if it is a supported file format. http://opencv.jp/opencv-2svn/cpp/highgui_reading_and_writing_images_and_video.html?highlight=write#imwrite

Development environment

Windows10 python3.7.7 pillow=7.1.2

"Convert a grayscale image (8bits / pixel) to a binary image (1bit / pixel)"

Let's actually show the source code. This time, we are converting from a grayscale image (8bits / pixel) to a binary image (1bit / pixel). It is also possible to convert a full-color image (8 bits / pixel for each of RGB) to a binary image (1 bit / pixel). In that case, comment out if inimg.mode == "L" :. (Don't forget the else)

gray2bin.py


import os
import glob

from PIL import Image

if __name__ == "__main__":
    get_dir = os.walk("./input")

    #Get the current directory
    current_dir = os.getcwd()

    #Get input directory
    indir = current_dir + "\\input\\"

    #Get output directory
    outdir = current_dir + "\\output_bin\\"

    #Create if there is no output folder
    if os.path.isdir(outdir) == False:
        os.mkdir(outdir)

    #Select an image in the input directory
    all_images = glob.glob(indir + "\\*")

    #Processing for each image
    for img in all_images:

        #Get the image name of the input image (with extension)
        basename = os.path.basename(img)
        print(basename)

        #Separate the extension from the image name of the input image
        name, ext = os.path.splitext(basename)

        #Save destination of the image converted to binary image
        save_path = outdir + name + "_bin.png " #pbm or bmp is fine
        #save_path = outdir + name + "_bin.bmp"


        if ext != ".bat" and ext != ".txt":
            with Image.open(img) as inimg:

                # print("inimg mode:",inimg.mode) # inimg mode: RGB

                # L(grayscale)If you want to binarize without asking questions, comment out.
                if inimg.mode == "L":

                    conv_image = inimg.convert("1")
                    #print("inimg.mode:", conv_image.mode)

                    conv_image.save(save_path)

                else:
                    print("inimg mode(not L):", inimg.mode)

Summary

This time, using "Converting a grayscale image (8bits / pixel) to a binary image (1bit / pixel)" as an example, I explained the points to note when saving a binary image (1bit / pixel).

The file formats described here (png / bmp, etc.) are not typical, but not all. We hope that you will try various other file formats to suit your needs.

If you have any comments, please let us know. (I want to be able to publish it on github from the next time.)

Recommended Posts

[Caution] When creating a binary image (1bit / pixel), be aware of the file format!
Be careful when differentiating the eigenvectors of a matrix
Diff a binary file (image file, etc.)
Things to be aware of when building a recommender system using Item2Vec
[Python memo] Be careful when creating a two-dimensional array (list of lists)
Be careful of the type when making an image mask with Numpy
The story of Django creating a library that might be a little more useful
Try modifying the TortoiseHg file view a bit
When a file is placed in the shared folder of Raspberry Pi, the process is executed.
Output the output result of sklearn.metrics.classification_report as a CSV file
Creating a list when the nomenclature is a fixed time