python - 函数 'cvtColor' 中的 OpenCV 错误 : (-215:Assertion failed) ! _src.empty()

标签 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 度时它起作用了。

最佳答案

我试过你的代码。它工作正常。虽然我在裁剪图像的那一行做了轻微的修改。你正在做的是 roi = im[x1:x2, y1:y2] 但它应该是 roi = im[y1:y2, x1:x2]。检查this有关如何使用 numpy 切片 裁剪图像的更多信息,请参阅 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

不知道你是有意还是无意,请验证一次。

关于python - 函数 'cvtColor' 中的 OpenCV 错误 : (-215:Assertion failed) ! _src.empty(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836263/

相关文章:

python - 使用 __stop 停止的线程不会从 threading.enumerate() 中删除

python - windows机器上可以同时安装Python3.6和Python3.8版本吗

python - 使用python进行帧差异

java - 在 Java 中使用 OpenCV 比较图像相似度

python - line_profiler 未按预期工作

python - 使用 Python 进行 2D 热传导

python - 如何在 C++ 中使用 ZeroMQ 传送多个图像?

c++ - 使用OpenCv的矩阵运算(加法和减法)OpenCV C++

c++ - cv::Mat 外部数据在使用 cv::imdecode 后未被修改

matlab - 在 Matlab 中计算 opencv 的透视变换时出错