python中的opencv如何获取轮廓下顶点的坐标
时间: 2024-05-12 11:16:43 浏览: 116
python-opencv获取二值图像轮廓及中心点坐标的代码
5星 · 资源好评率100%
您可以使用OpenCV的findContours函数来获取图像中的轮廓。在该函数的参数中,您需要指定要查找轮廓的图像以及要使用的轮廓查找模式。在找到轮廓后,您可以使用approxPolyDP函数来近似多边形,然后使用approxPolyDP函数返回的多边形边缘点数组来获取多边形的边缘点坐标。您还可以使用minAreaRect函数来获取多边形的外包矩形,然后使用boxPoints函数来获取矩形顶点的坐标。以下是一个获取轮廓顶点坐标的示例代码:
```
import cv2
# Load image and convert to grayscale
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find contours in the image
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Iterate through each contour
for contour in contours:
# Approximate contour with a polygon
epsilon = 0.01 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# Draw polygon on original image
cv2.drawContours(img, [approx], 0, (0, 255, 0), 3)
# Get coordinates of polygon vertices
vertices = approx.ravel().reshape(-1, 2)
# Print coordinates of vertices
for vertex in vertices:
print(vertex)
# Fit a bounding box to the polygon
rect = cv2.minAreaRect(approx)
box = cv2.boxPoints(rect)
# Draw bounding box on original image
cv2.drawContours(img, [box.astype(int)], 0, (0, 0, 255), 2)
# Display the original image with contours and bounding boxes
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文