Python opencv:在点之间画线并找到完整的轮廓

时间:2021-04-02 18:09:53

标签: python python-3.x numpy opencv

我有一组三个点,在一个三角形中。例如:[[390 37]、[371 179]、[555 179]]

绘制线条后,How to draw lines between points in OpenCV?

如何在我刚刚绘制的线条之间找到完整的轮廓?

我不断收到以下错误:

    img = np.zeros([1000, 1000, 3], np.uint8)
    cv2.drawContours(img, triangle_vertices, 0, (0, 0, 0), -1)
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
<块引用>

错误:(-210:不支持的格式或格式组合)[Start]FindContours 在 mode != CV_RETR_FLOODFILL 时仅支持 CV_8UC1 图像,否则仅在函数 'cvStartFindContours_Impl' 中支持 CV_32SC1 图像

1 个答案:

答案 0 :(得分:2)

我相信您的主要问题是您只能在二值图像(而不是颜色)上找到轮廓。你的点也需要在一个 Numpy 数组中(作为 x,y 对——注意逗号)。下面是我在 Python/OpenCV 中的做法。

import cv2
import numpy as np

# create black background image
img = np.zeros((500, 1000), dtype=np.uint8)

# define triangle points
points = np.array( [[390,37], [371,179], [555,179]], dtype=np.int32 )

# draw triangle polygon on copy of input
triangle = img.copy()
cv2.polylines(triangle, [points], True, 255, 1)

# find the external contours
cntrs = cv2.findContours(triangle, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]

# get the single contour of the triangle
cntr = cntrs[0]

# draw filled contour on copy of input
triangle_filled = img.copy()
cv2.drawContours(triangle_filled, [cntr], 0, 255, -1)

# save results
cv2.imwrite('triangle.jpg', triangle)
cv2.imwrite('triangle_filled.jpg', triangle_filled)

cv2.imshow('triangle', triangle)
cv2.imshow('triangle_filled', triangle_filled)
cv2.waitKey()

三角形多边形图像:

enter image description here

三角形填充轮廓图像:

enter image description here

相关问题