cv2.approxPolydp() return 是什么意思?

What does cv2.approxPolydp() return?

我正在尝试根据应用 cv2.approxPolyDP() 后检测到的轮廓调整图像大小。之后,我必须根据 cv2.approxPolyDP().

检测到的轮廓的 return 值使用 cv2.resize() 自定义裁剪尺寸以进行裁剪

我想知道哪个 index 是高度,哪个索引是宽度 起始 x,y 坐标和结束 x,y 坐标。

def biggestContour(contours):
    biggest = np.array([])
    max_area = 0
    for i in contours:
        area = cv2.contourArea(i)
        if area > 5000:
            peri = cv2.arcLength(i, True)
            approx = cv2.approxPolyDP(i, 0.02 * peri, True)
            if area > max_area and len(approx) == 4:
                biggest = approx
                max_area = area
    return biggest,max_area

考虑到这段代码,我如何找到哪个索引是高度,哪个索引是宽度或起始 x,y 坐标和结束 x,y 坐标?

cv2.approxPolyDP return 是一个重新采样的轮廓,所以这仍然是 return 一组 (x, y) 点。如果你想裁剪出这个结果,returned 轮廓应该是一个 N x 1 x 2 NumPy 数组,所以去掉单例维度,然后在 x 和 y 坐标上做标准的 min/max 操作来得到左上角和右下角,最后裁剪。假设要裁剪的图像称为 img,并且根据 cv2.findContours 计算的轮廓列表称为 contours,请尝试:

# Find biggest contour
cnt, area = biggestContour(contours)

# Remove singleton dimensions
points = np.squeeze(cnt)

# Extract rows and columns
y = points[:, 0]
x = points[:, 1]

# Now crop
(topy, topx) = (np.min(y), np.min(x))
(bottomy, bottomx) = (np.max(y), np.max(x))
out = img[topy:bottomy+1, topx:bottomx+1]

out 现在将包含裁剪后的图像。