Reputation: 442
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.
Upvotes: 7
Views: 27414
Reputation: 1
Your cv2.imread
is reading a RGB image. To read in grayscale it is
image = cv2.imread("disparitySGB.jpg", 0)
Upvotes: 0
Reputation: 1
You just need to 'import numpy as np' and your original code should work fine.
Upvotes: 0
Reputation: 21851
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.
Upvotes: 12
Reputation: 6090
cv2.inRange(src, lowerb, upperb[, dst]) → dst
Takes src
as array and lower
and upper
as array
or a scalar
, this means you can use it to Threshold Grayscale images. You just have to use scalars
for upper
and lower
.
Example:
myResult = cv2.InRange(myGrayscale, 50, 100)
Upvotes: 1