如何在OpenCV中获取已识别目标的坐标?
获取OpenCV高亮目标的坐标
你已经通过cv2.findContours得到了轮廓集合contours,每个轮廓本身就是由目标边缘的(x,y)像素坐标点组成的数组。下面是几种实用的坐标获取方式:
1. 获取轮廓的所有原始坐标点
每个contour是形状为(N,1,2)的numpy数组,N代表轮廓上的点数,直接遍历即可提取每个点的坐标:
for idx, contour in enumerate(contours): print(f"第{idx+1}个轮廓的坐标点:") for point in contour: x, y = point[0] print(f"({x}, {y})")
2. 获取目标的外接矩形坐标
用cv2.boundingRect可以快速得到目标的外接矩形参数,返回值(x, y, w, h)中:
- (x,y)是矩形左上角的像素坐标
- w是矩形宽度,h是矩形高度
for idx, contour in enumerate(contours): x, y, w, h = cv2.boundingRect(contour) print(f"第{idx+1}个目标的外接矩形:左上角({x},{y}),宽{w},高{h}") # 可选:在图像上绘制外接矩形 cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
3. 获取目标的中心坐标
两种常用计算方式:
方法1:通过外接矩形计算
for contour in contours: x, y, w, h = cv2.boundingRect(contour) center_x = x + w // 2 center_y = y + h // 2 print(f"中心坐标:({center_x}, {center_y})")
方法2:通过轮廓矩计算(更精准)
for contour in contours: M = cv2.moments(contour) if M['m00'] != 0: # 避免除以0 center_x = int(M['m10'] / M['m00']) center_y = int(M['m01'] / M['m00']) print(f"中心坐标:({center_x}, {center_y})")
完整示例代码
整合坐标获取和可视化的完整代码:
import cv2 import matplotlib.pyplot as plt img = cv2.imread('test.png') gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray_img, 125, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 遍历所有轮廓,获取坐标并标记 for idx, contour in enumerate(contours): # 获取外接矩形 x, y, w, h = cv2.boundingRect(contour) # 计算中心坐标 center_x = x + w // 2 center_y = y + h // 2 # 打印坐标信息 print(f"目标{idx+1}:") print(f"外接矩形左上角:({x}, {y}),宽:{w},高:{h}") print(f"中心坐标:({center_x}, {center_y})\n") # 绘制轮廓和中心标记 img = cv2.drawContours(img, [contour], -1, (255, 0, 0), 2) cv2.circle(img, (center_x, center_y), 3, (0, 255, 0), -1) # OpenCV默认BGR通道,转RGB后用matplotlib显示 plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show()
注意:OpenCV读取的图像是BGR颜色通道,用matplotlib显示时需要转成RGB,否则颜色会出现偏差。
内容的提问来源于stack exchange,提问作者user582426
相关产品推荐
相关产品推荐

