These days I have made some image processing work, and I have the opportunity to try the python I learned a long time ago. The result is surprising to myself, and it is much better than my original optimism.
Of course, first of all, I would like to thank "Love Butterfly" for his article "Using python for image processing", which helped me solve the problem with Python and Pil, for some introduction and basic operations on Pil, please refer to this article. Here I will mainly introduce my experience in the use process.
Set the threshold for Binary Image Conversion
PIL can be used to convert the color of an image, and supports 24-bit color, 8-bit grayscale, and Binary Map modes. after the convert (mode) function is complete, mode indicates the color mode of the output. For example, 'L' indicates the gray level, and '1' indicates the Binary Graph mode. However, when the convert function is used to convert a grayscale image to a binary image, a fixed threshold value of 127 is used, that is, the pixel value above 127 is 1, the pixel value of gray scale less than 127 is 0. The image. Point function is used to convert gray-scale images to two-value images through custom thresholds.
Image. the point function has multiple forms. Only image is discussed here. point (table, mode). This function can be used to convert pixel colors in the form of table queries. Table is the ing table during color conversion, each color channel should have 256 elements, while the mode indicates the output color mode. Similarly, 'L' indicates the gray level, and '1' indicates the two-value graph mode. It can be seen that the key to the conversion process is to design the ing table. If you only need a Simple clamping value, you can set the elements in the table above or below the clamping value to 1 and 0 respectively. Of course, because the table here does not have any special requirements, you can implement any one-to-one ing relationships within the range (0,255) through special settings on the elements.
The sample code is as follows: Import image
# Load a color image
Im = image.open('fun.jpg ')
# Convert to Gray Level Image
Lim = Im. Convert ('l ')
Lim.save('fun_level.jpg ')
# Setup a converting table with constant threshold
Threshold = 80
Table = []
For I in range (256 ):
If I <threshold:
Table. append (0)
Else:
Table. append (1)
# Convert to binary image by the table
BIM = lim. Point (table, '1 ')
Bim.save('fun_binary.jpg ')
Original Image (fun.jpg ):
Grayscale (fun_level.jpg), Threshold = 80:
Binary diagram (fun_binary.jpg ):
Grayscale (fun_level.jpg), Threshold = 80:
Play by foxsaver play by foxsaver