Applying adaptive threshold to a grayscale image

2k views Asked by At

I have a png image which is in grayscale 'test.png'. I need apply adaptive threshold to this image. I am using OpenCV.

image = cv2.imread('test_big.png')
im = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)

I am not able to apply adaptive threshold since the image is not in grayscale. So I tried to read the image as grayscale:

image = cv2.imread('test_big.png',1)

Now I can apply adaptive threshold but the output will be a blue and red image instead of black and white. Can anyone help?

1

There are 1 answers

1
Jeru Luke On BEST ANSWER

The fault lies in the second code snippet:

image = cv2.imread('test_big.png',1)

Although you have said that test_big.png is a grayscale image, you have declared it as a color image (RGB) with three channels.

Hence you have to change the code to

image = cv2.imread('test_big.png', 0)
  • 0 -> grayscale image
  • 1 -> color image

You can also try:

cv2.imread('test_big.png', cv2.IMREAD_GRAYSCALE)

The bottom line is: although the image being read is a grayscale image, the system will not recognize it until it is explicitly specified. In your case, your image was a grayscale image, but since you declared it as a color image it considered the image to have three channels (RGB) and hence the subsequent adaptive threshold function did not execute.