0

I want to binarize a gray image by value, so pixels that are between a and b will be 0, and 255 otherwise. I tried cv2.threshold but this didn't produce the right effect. So I tried:

def cut(img,d,u):
    for x,line in enumerate(img):
        for y,px in enumerate(line):
            if px < d or px > u:
                img[x][y]=0
            else:
                img[x][y]=255   

But this way is low performance, what is the right way to do that, use histogram equalization?

porglezomp
  • 1,333
  • 12
  • 24
novox
  • 143
  • 1
  • 10

2 Answers2

2

Have a look at inRange function.

You can do something like:

binary = cv2.inRange(gray_image, d, u)

You then probably need to invert the binary image:

binary_inv = cv2.bitwise_not(binary)
Miki
  • 40,887
  • 13
  • 123
  • 202
0

First, you need to make sure your image is in an allowed data format for opencv Then you should use the threshold function or inRange function to create the binary image/matrix according to your needs. With the threshold function, you'd need to apply it twice, since you have a range, but that's not too complicated. There's a really nice blog post on this here.

helloB
  • 3,472
  • 10
  • 40
  • 87
  • 1
    _Isn't too complicated_ isn't very useful. Consider posting a code snippet with your solution – Miki Sep 03 '15 at 14:29