OpenCV错误:(-215:断言失败)函数'cvtColor'

时间:2019-07-01 13:05:34

标签: python opencv

我正在使用opencv来操作图像。确切的错误是:

OpenCV(4.1.0) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

我在互联网上进行了搜索,但找不到解决方案。

同一张图片在此过程中被多次调用,并且大部分效果良好。 我在此函数中遇到错误:

def percentage(image, box_points):  #box point is touple here. ((x1,y1),(x2,y2))
    x1=box_points[0][0]
    x2=box_points[1][0]
    y1=box_points[0][1]
    y2=box_points[1][1]  
    rows,cols,c =image.shape
    M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
    image = cv2.warpAffine(image,M,(cols,rows))
    image=image[int(x1):int(x2),int(y1):int(y2)]
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # ret, bw_img = cv2.threshold(image,160,255,cv2.THRESH_BINARY)
    # bw_img = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 7)
    bw_img = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,11,2)
    # image=image[int(x1):int(x2),int(y1):int(y2)]
    # bw_img is our binary image here.
    count = cv2.countNonZero(bw_img)
    total = bw_img.shape[1] * bw_img.shape[0]
    ratio = count/total
    ratio =1-ratio
    return ratio, bw_img

在调用cv2.cvtColor的行中出现错误。该函数给出黑色像素与总像素的比率。在整个项目中多次调用同一张图像,因此该错误不应与缺少图像有关。

此外,在测试时,我将图像逆时针旋转了90度。这样做很好,但仅适用于一个特定的图像。在这里帮我。 enter image description here

我将在此处附加原始图像。当我旋转90度时,它可以工作。

1 个答案:

答案 0 :(得分:0)

我尝试了您的代码。一切正常。尽管我在裁剪图像的行上做了一些小的修改。您正在做的是roi = im[x1:x2, y1:y2],但应该是roi = im[y1:y2, x1:x2]。有关如何使用numpy slicing裁剪图像的更多信息,请参见this stackoverflow帖子。这可能是您收到上述错误的原因。您必须进行检查才能验证。

这一细微变化可能非常重要。检查以下比较:

两种情况下的函数调用:percentage(img, ((10, 10), (300, 600)))

案例1: image=image[int(x1):int(x2),int(y1):int(y2)]

enter image description here

案例2: image=image[int(y1):int(y2), int(x1):int(x2)]

enter image description here

我不知道您是否故意进行此操作,但请确认一次。