The following code block shows how to to use the PIL point()function for thresholding with a fixed threshold:
im = Image.open('../images/swans.jpg').convert('L')
pylab.hist(np.array(im).ravel(), bins=256, range=(0, 256), color='g')
pylab.xlabel('Pixel values'), pylab.ylabel('Frequency'),
pylab.title('Histogram of pixel values')
pylab.show()
pylab.figure(figsize=(12,18))
pylab.gray()
pylab.subplot(221), plot_image(im, 'original image'), pylab.axis('off')
th = [0, 50, 100, 150, 200]
for i in range(2, 5):
im1 = im.point(lambda x: x > th[i])
pylab.subplot(2,2,i), plot_image(im1, 'binary image with threshold=' + str(th[i]))
pylab.show()
The following screenshots show the output of the previous code. First, we can see the distribution of the pixel values in the input image from the following:
Also, as can be seen from the following, the binary images obtained with different gray-level thresholds are not shaded properly—resulting in an artefact known as false contours:
We shall discuss a few different thresholding algorithms in more details in Chapter 6, Morphological Image Processing, when we discuss image segmentation.