python - boxPoints 返回负 y 值

标签 python python-3.x opencv

我正在尝试在简单图像上绘制最小框轮廓。

Original Image

但是,从 boxPoints() 函数返回的点之一给我一个负 y 值。绘制此轮廓时,此角是从图像中绘制出来的。

Resulting Outline

我不确定为什么它返回负 y 值。我使用的是图像的二进制版本,因此最大的轮廓应该是便利贴的轮廓。其他角之一也未正确拾取。不太确定如何解决这个问题。见下面的代码:

def contours(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    gray = cv2.dilate(gray, None)  # fill some holes
    gray = cv2.dilate(gray, None)
    gray = cv2.erode(gray, None)  # dilate made our shape larger, revert that
    gray = cv2.erode(gray, None)

    # first threshold the image to create a binary image of black and white
    ret, thresh = cv2.threshold(gray, 127, 255, 0)

    # contours output var is a list of each coordinate in the contour
    # use CHAIN_APPROX_SIMPLE to pick only necessary contour points rather than all points on the contour
    img,cnt,hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # get the min area rect
    rect = cv2.minAreaRect(cnt[0])
    print(rect)
    box = cv2.boxPoints(rect)
    print(box)
    # convert all coordinates floating point values to int
    box = np.int32(box)
    cv2.drawContours(image, [box], 0, (0, 0, 255))
    cv2.imshow('Corners1', image)
    cv2.waitKey(0)

打印的 minAreaRect 和 boxPoints 如下:

((182.83834838867188, 139.0049591064453), (208.65762329101562, 247.1478271484375), -31.165145874023438)
[[ 157.5166626   298.73544312]
 [  29.61603546   87.25617981]
 [ 208.16003418  -20.7255249 ]
 [ 336.06066895  190.7537384 ]]

最佳答案

看起来您正在使用此库中的框函数。你可以看到,在生成的图像上,所有角度都是 90 度,所以你需要做的是制作多边形而不是矩形。负 y 值是这个直角框的结果。

关于python - boxPoints 返回负 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47272306/

相关文章:

python - 将 2D numpy 数组重新缩放为密集表示

python-3.x - 模拟 : Client does not have the attribute 'get_object'

python - 如何通过匹配字典值将二级列标题/索引添加到数据框?

python + opencv - 如何正确比较图像(通过直方图)?

c++ - 顺时针旋转二维矩阵会产生奇数结果

python - 如何获取 Datetime 的完整日期长度

python - 设置 ImageGrab 从中获取像素颜色的位置

python - 在 Pyramid 中导入它们时如何缩短路径?

python - 如何检查与可以放置在 pygame 中任何位置的对象的碰撞

android - OpenCV4Android 类 Mat : difference between width() and rows(), 以及 height() 和 cols() 之间的类?