tr2002a
tr2002a

Reputation: 116

How do I threshold to zero using adaptive thresholding in opencv?

I'm trying to use cv2.adaptiveThreshold() but for my purposes, it would be ideal if I could threshold to zero rather than to binary. I tried using the flag cv2.THRESH_TOZERO like you can with cv2.threshold() but it threw an error. How could I do this, and if I can't do it with adaptiveThreshold(), how can I do it otherwise? Thanks for any help.

Upvotes: 2

Views: 1154

Answers (2)

Masoud
Masoud

Reputation: 1280

From opencv documentation, cv2.adaptiveThreshold has only two thresholding types:

Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV .

So for adaptive shareholding, if similar behavior of cv2.THRESH_TOZERO is desired, its possible to multiply original image and binary image resulted from thresholding. For example:

thresh_binary = cv2.adaptiveThreshold(img, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 220)
thresh_tozero = cv2.multiply(img, thresh_binary)

Upvotes: 1

tr2002a
tr2002a

Reputation: 116

I figured it out. Thanks anyways for your help @Masoud! I used this code:

    imgb = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \ 
    cv2.THRESH_BINARY, 255, -9)
    img[np.where(imgb == 0)] = 0

I used numpy to find where the binary image was equal to zero, and I set the original grayscale image to zero in those locations.

Upvotes: 2

Related Questions