Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thresholding of a grayscale Image in a range

Tags:

python

opencv

Does OpenCV cv.InRange function work only for RGB images?Can I do thresholding of grayscale image using this function?

I got an error,Following is my code:

   import cv2
   image=cv2.imread("disparitySGB.jpg")
   thresh=cv2.inRange(image,190,255);

It gives the following error:

thresh=cv2.inRange(image,190,255); TypeError: unknown is not a numpy array

I tried fixing it by:

  thresh=cv2.inRange(image,numpy.array(190),numpy.array(255));

Now there is no error but it produces black image.

like image 838
Maham Avatar asked Nov 18 '13 14:11

Maham


1 Answers

For a gray-valued image which has shape (M, N) in numpy and size MxN with one single channel in OpenCV, then cv2.inRange takes scalar bounds:

gray = cv2.imread(filename, cv2.CV_LOAD_IMAGE_GRAYSCALE)
gray_filtered = cv2.inRange(gray, 190, 255)

But for RGB-images which have shape (M, N, 3) in numpy and size MxN with three channels in OpenCV you need to have the bounds match the "channel size".

rgb = cv2.imread(filename, cv2.CV_LOAD_IMAGE_COLOR)
rgb_filtered = cv2.inRange(gray, (190, 190, 190), (255, 255, 255))

This is explained in the documentation, although not very clearly.

like image 178
Hannes Ovrén Avatar answered Oct 26 '22 09:10

Hannes Ovrén