python 如何获取轮廓内的所有坐标画出来
时间: 2024-04-09 08:32:55 浏览: 13
要获取轮廓内的所有坐标并将其画出来,可以使用cv2.findContours函数找到轮廓,并使用cv2.drawContours函数将轮廓绘制在一个图像上。然后,可以使用cv2.fillPoly函数将轮廓内的区域填充为白色,并使用cv2.findNonZero函数找到白色区域的所有坐标。
下面是一个示例代码,演示如何获取轮廓内的所有坐标并画出来:
```python
import cv2
# 读取图像
image = cv2.imread('image.jpg')
# 将图像转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建一个与原始图像大小相同的黑色图像
mask = np.zeros_like(image)
# 遍历轮廓
for contour in contours:
# 将轮廓绘制在图像上
cv2.drawContours(mask, [contour], -1, (255, 255, 255), thickness=cv2.FILLED)
# 找到白色区域的所有坐标
points = cv2.findNonZero(mask)
# 在原始图像上绘制轮廓内的所有坐标
for point in points:
x, y = point[0]
cv2.circle(image, (x, y), 1, (0, 255, 0), -1)
# 显示绘制结果
cv2.imshow("Contour Coordinates", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,该代码假设图像中只有一个轮廓。如果图像中有多个轮廓,您可能需要根据自己的需求进行适当的处理。