These days doing some image processing, just to have a chance to try Python learned a long time ago, the result is very surprising to me, than my original optimistic imagination is more useful.
Of course, first of all to thank the "Flower Butterfly", is his article "Using Python image processing" To help me strengthen the use of Python and PIL problem-solving ideas, for PiL some introduction and basic operations, you can see this article. My main point here is to introduce my experience in the use process.
Setting thresholds for binary image conversions
PIL can convert the color of an image, and support patterns such as 24-bit color, 8-bit grayscale and two-value graphs, simple transformations can be done through the Image.convert (mode) function, where mode represents the color pattern of the output, for example, ' L ' means grayscale, ' 1 ' Represents a two-valued graph pattern, and so on. However, using the CONVERT function to convert the grayscale map to a two-value graph, it is implemented by a fixed threshold 127来, that is, the pixel value of grayscale above 127 is 1, and the pixel value of grayscale below 127 is 0. In order to realize the conversion of grayscale graph to two value graph through the custom threshold value, the Image.point function is used.
The Image.point function has several forms, where only the image.point (table, mode) is discussed, which enables you to implement pixel-color pattern conversions by look-up tables, where table is the mapping table in the color conversion process, and each color channel should have 256 elements. and mode represents the output color pattern, the same, ' L ' means grayscale, ' 1 ' represents a binary graph pattern. Visible, the key to the conversion process is to design the mapping table, if you just need a simple clamping value, you can set the table above or below the clamping value of the elements to 1 and 0 respectively. Of course, because the table here does not have any special requirements, so you can through the special set of elements to achieve (0, 255) within the scope of any required one-to-one mapping relationship.
The sample code is as follows:
Import Image
# Load a color image
im = Image.open (' fun.jpg ')
# Convert to Grey 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 picture (fun.jpg):
Grayscale chart (fun_level.jpg), threshold=80:
Two-value graph (fun_binary.jpg):
Grayscale chart (fun_level.jpg), threshold=200: