简体   繁体   English

在范围内对灰度图像进行阈值处理

[英]Thresholding of a grayscale Image in a range

Does OpenCV cv.InRange function work only for RGB images?Can I do thresholding of grayscale image using this function? OpenCV cv.InRange功能是否仅适用于RGB图像?我可以使用此功能对灰度图像进行阈值处理吗?

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); 脱粒= cv2.inRange(图像,190255); TypeError: unknown is not a numpy array TypeError:unknown不是一个numpy数组

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. 现在没有错误,但它会产生黑色图像。

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: 对于具有numpy形状(M,N)并且在OpenCV中具有单个通道的大小为MxN的灰度值图像,则cv2.inRange采用标量边界:

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". 但对于具有numpy形状(M,N,3)并且在OpenCV中具有三个通道的MxN大小的RGB图像,您需要使边界与“通道大小”匹配。

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. 这在文档中有解释,但不是很清楚。

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. src作为数组,将lowerupper作为arrayscalar ,这意味着您可以将其用于阈值灰度图像。 You just have to use scalars for upper and lower . 你只需要使用scalarsupperlower

Example: 例:

myResult = cv2.InRange(myGrayscale, 50, 100)

你只需要'导入numpy as np',你的原始代码应该可以正常工作。

Your cv2.imread is reading a RGB image. 你的cv2.imread正在读取RGB图像。 To read in grayscale it is 要以灰度读取它

image = cv2.imread("disparitySGB.jpg", 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM