python - Python中的OpenCV2使用inRange抛出错误

标签 python opencv

所以我看起来很努力,但我找不到关于 OpenCV 错误的任何内容,而且绝对没有讨论可能的错误及其原因的文档。我正在将 OpenCV2 与 Python 2.7 一起使用,试图通过网络摄像头实时跟踪彩色泡泡球。为此,我通过对来自网络摄像头的最新图像进行阈值处理,围绕粉扑球出现的 HSV 值来获得彩色球的中心。不幸的是,这似乎并不总是有效,并引发了一个非常神秘的错误:

cv2.error: .../matrix.cpp:235: error: (-215) step[dims-1] == (size_t)CV_ELEM_SIZE(flags) in function create

我不知道为什么它会抛出这个。产生它的代码是:
    def getColorCenter(self, imgHSV, lowerBound, upperBound, debugName = None):
        detectedImg = cv2.inRange(imgHSV, lowerBound, upperBound)

        if str(lowerBound) == str(self.GREEN_LOWER_BOUND):
            cv2.imshow(str(lowerBound) + "puffball", detectedImg)

        center = self.getCenterOfLargestBlob(detectedImg, debugName)
        return center

尤其是 detectedImg = cv2.inRange(imgHSV, lowerBound, upperBound) 行.

知道什么可以解决这个问题吗?

最佳答案

如果网络摄像头未检测到任何 blob,则可能会导致该错误。

解决问题的更好方法是使用轮廓。
您可以遍历图像中的所有轮廓并选择面积最大的轮廓。然后您可以返回最大轮廓的质心。

detectedImg = cv2.inRange(imgHSV, lowerBound, upperBound)

# If there is a lot of noise in your image it would help to open and dilate

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))

detectedImg_open = cv2.morphologyEx(detectedImg, cv2.MORPH_OPEN, kernel)
detectedImg_dilate = cv2.dilate(detectedImg_open, kernel, iterations = 1)

现在找到轮廓:
_, contours, _ = cv2.findContours(detectedImg_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

按面积求最大等高线:
largest_contour_val = 0
largest_contour_pos = 0
for i in xrange(len(contours)):
    if cv2.contourArea(contours[i])>largest_contour_val:
        largest_contour_val = cv2.contourArea(contours[i])
        largest_contour_pos = i

现在只有存在至少一个轮廓时,我们才返回最大轮廓的质心:
if len(contours)!=0:

    # find centroid and return it
    M = cv2.moments(contours[largest_contour_pos])
    x = int(M['m10']/M['m00'])
    y = int(M['m01']/M['m00'])
    center = (x,y)
    return center

关于python - Python中的OpenCV2使用inRange抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495587/

相关文章:

python - EC2 响应错误 : 401 Unauthorized AWS was not able to validate the provided access for an ec2 instance

python - 使用 rdflib 打印出本体中每个概念的个体

python - 如何在循环中制作双 'continue'?

opencv - 使用opencv进行形状检测的形状

python - 如何在Python中将整数转换为无符号32位?

python - matplotlib:分组箱线图

opencv - 如何细化或模糊或平滑边缘?

c++ - 在 Qiana 上构建 opencv 失败

c++ - opencv矩阵多 channel 获取和填充

opencv - 使用 OpenCv 保存时图像透明度变暗