Import the required modules.
%pylab inline
import cv2
Populating the interactive namespace from numpy and matplotlib
First of all read the image, then convert the image to grayscale and finally display the image.
im = imread("/home/bikz05/Desktop/image.jpg")
im_gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
axis("off")
title("Input Image")
imshow(im_gray, cmap = 'gray')
show()
We will first perform fixed thresholding on the input image. Fixed Thresholding is done using the function cv2.threshold
.
The signature of cv2.threshold
is -
cv2.threshold(src, thresh, maxval, type[, dst]) -> retval, dst
Here,
src
is the input image.thresh
is the threshold value.maxval
is the maximum value that can be assigned to the output.type
is the type of thresholding.dst
is the destination imageThe threshold value set is 50 and the threshold type is cv2.THRESH_BINARY
i.e. any value that is greater than 50 is set to 255 and any value less than 55 is set to 0.
retval, im_at_fixed = cv2.threshold(im_gray, 50, 255, cv2.THRESH_BINARY)
axis("off")
title("Fixed Thresholding")
imshow(im_at_fixed, cmap = 'gray')
show()
Adaptive Thresholding with mean weighted average is done using the function cv2.adaptiveThreshold
.
The signature of the function is -
cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
Here,
src
is the input image.adaptiveMethod
is set to cv2.ADAPTIVE_THRESH_MEAN_C for mean weighted average and to cv2.ADAPTIVE_THRESH_GAUSSIAN_C for gaussian weighted average.thresholdType
- the type of thresholdingblockSize
- value of bC
- the constant that is subtracted from the threshold value calculated for each pixeldst
is the destination imageFor the example, the value of b
is 5 and the constant value is set to 10.
im_at_mean = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10)
axis("off")
title("Adaptive Thresholding with mean weighted average")
imshow(im_at_mean, cmap = 'gray')
show()
Adaptive Thresholding with gaussian weighted average is done using the function cv2.adaptiveThreshold
.
The signature of the function is -
cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
Here,
src
is the input image.adaptiveMethod
is set to cv2.ADAPTIVE_THRESH_MEAN_C for mean weighted average and to cv2.ADAPTIVE_THRESH_GAUSSIAN_C for gaussian weighted average.thresholdType
- the type of thresholdingblockSize
- value of bC
- the constant that is subtracted from the threshold value calculated for each pixeldst
is the destination imageFor the example, the value of b
is 5 and the constant value is set to 7.
im_at_gauss = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 7)
axis("off")
title("Adaptive Thresholding with gaussian weighted average")
imshow(im_at_gauss, cmap = 'gray')
show()
That's it! Clearly results are better with adaptive thresholding as compared to fixed thresholding.