简体   繁体   English

在灰度图像上使用自适应阈值的错误

[英]Error in using adaptive thresholding on gray-scale image

I read an image, and converted it to gray-scale using this function:我读取图像,并使用此函数将其转换为灰度:

def rgb2gray(img):
    if len(img.shape)==3 & img.shape[-1] == 3:  # img is RGB
        return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return img

now, I try to convert my image to binary using this:现在,我尝试使用以下方法将图像转换为二进制:

def apply_threshold(img):
    if len(np.unique(img))==2: #img is already binary
        return img
    gray_img=rgb2gray(img)
    _,binary_img=cv2.threshold(gray_img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return binary_img

but I get this annoying error:但我收到了这个烦人的错误:

cv2.error: OpenCV(3.4.1) C:\projects\opencv-python\opencv\modules\imgproc\src\thresh.cpp:1406: error: (-215) src.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3)) in function cv::threshold

I can't understand why since gray_img is for sure gray-scale!我不明白为什么因为gray_img肯定是灰度的! I looked at this question, and the top answer by salvador daly proposed that the input picture is not gray-scale, but I checked it multiple times and it for sure is.我看了这个问题, salvador daly的最高回答提出输入图片不是灰度的,但我检查了多次,确实是。

Any help will be appreciated!任何帮助将不胜感激!

You can try this approach for getting the threshold version/binary image of color image.您可以尝试这种方法来获取彩色图像的阈值版本/二进制图像。

""" Read the original image in color form"""
image = cv2.imread(r'image.png') 

""" Convert the image to gray scale"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

""" reducing the Noise """
blur = cv2.GaussianBlur(gray, (3,3), 0)

""" Applying Otsu thresholding """
_, thres = cv2.threshold(blur, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)

or if you want adaptive threshold of image, you can try this as well或者如果你想要图像的自适应阈值,你也可以试试这个

thres = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY_INV,15,2)

for more details on thresholding you can check this site https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html有关阈值的更多详细信息,您可以查看此站点https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html

also you can check whether the image is of color or gray scale version by checking the shape of the channels of image.您也可以通过检查图像通道的形状来检查图像是彩色版还是灰度版。

  • The color image has 3 channels or 3-D matrix ( Red, Green and Blue) so the dimension of the image matrix will be W x H x C (width x height x channel ) for eg 300 x 300 x 3彩色图像有 3 个通道或 3-D 矩阵(红色、绿色和蓝色),因此图像矩阵的维度将为 W x H x C(宽 x 高 x 通道),例如 300 x 300 x 3
  • The grayscale or binary image has only one channel (gray scale) or it is only 2-D matrix.灰度或二值图像只有一个通道(灰度)或只有二维矩阵。 for eg 300 x 300.例如 300 x 300。

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

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