在灰度图像上使用自适应阈值处理时出错

时间:2018-10-10 19:37:55

标签: python opencv image-processing cv2 image-thresholding

我读取图像,并使用此功能将其转换为灰度:

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肯定是灰度的! 我看了一个this问题,salvador daly的最高答案提出输入图片不是灰度的,但我对其进行了多次检查,并确定是。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

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

let response = [
  { id: '45:32:BC:3E:67:CD', name: 'beacon1', rssi: -78, region: 1 },
  { id: '71:B2:51:E7:91:C0', name: 'beacon2', rssi: -52, region: 1 },
  { id: '73:CD:84:44:DA:BE', name: 'beacon3', rssi: -53, region: 1 },
  { id: '4F:6E:FA:E7:E1:5B', name: 'beacon4', rssi: -53, region: 1 }
]
const result = response.reduce((acc, { name, region, rssi }) => ( { ...acc, region, [name]: rssi } ), {} );

console.log(result);

或者如果您想要图像的自适应阈值,也可以尝试

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

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

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

  • 彩色图像具有3个通道或3-D矩阵(红色,绿色和蓝色),因此图像矩阵的尺寸为W xH x C(宽度x高度x通道),例如300 x 300 x 3 < / li>
  • 灰度或二进制图像只有一个通道(灰度),或者只有二维矩阵。例如300 x 300。
相关问题