0

我读取了一张图像,并使用此函数将其转换为灰度:

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

现在,我尝试使用以下方法将我的图像转换为二进制:

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

但我收到了这个烦人的错误:

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

我不明白为什么因为gray_img肯定是灰度的!我看了这个问题,上面的答案是salvador daly提出输入图片不是灰度的,但是我检查了很多次,肯定是。

任何帮助将不胜感激!

4

1 回答 1

0

您可以尝试这种方法来获取彩色图像的阈值版本/二进制图像。

""" 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)

或者如果你想要图像的自适应阈值,你也可以试试这个

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

有关阈值的更多详细信息,您可以查看此站点 https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html

您也可以通过检查图像通道的形状来检查图像是彩色版本还是灰度版本。

  • 彩色图像具有 3 个通道或 3-D 矩阵(红色、绿色和蓝色),因此图像矩阵的尺寸将为 W x H x C(宽度 x 高度 x 通道),例如 300 x 300 x 3
  • 灰度或二值图像只有一个通道(灰度)或只有二维矩阵。例如 300 x 300。
于 2020-03-09T06:39:43.697 回答