如何提取每个正方形bounding box的中心点坐标并存入元组列表

需求
获取每个橙色正方形的中心点坐标(即边界框内标注的蓝色点),将坐标存储为元组列表。当前使用的检测代码如下:
import cv2 as cv import numpy as np from cvzone.ColorModule import ColorFinder import cvzone img = cv.imread("image_path") myColorFinder = ColorFinder(False) hsvValsOrange = {'hmin': 0, 'smin': 164, 'vmin': 0, 'hmax': 179, 'smax': 255, 'vmax': 255} imgColor,mask = myColorFinder.update(img,hsvValsOrange) imgContour, contours = cvzone.findContours(img,mask, minArea=1000) if len(contours): data = contours[0]["center"][0],h-contours[0]["center"][1],int(contours[0]["area"]) print(data) imgStack = cvzone.stackImages([img,imgColor,mask,imgContour],2,0.5) cv.imshow("Image", imgStack) cv.waitKey(0) cv.destroyAllWindows()
现存问题
- 代码仅读取了
contours列表的第一个元素,只能获取1个橙色块的信息,无法拿到所有检测目标 - 代码中使用的
h(图像高度)变量未提前定义,运行会触发报错
修正方案
读取图像后先获取图像尺寸,遍历所有检测到的有效轮廓,逐个提取中心点信息存入元组列表即可,修正后代码:
import cv2 as cv import numpy as np from cvzone.ColorModule import ColorFinder import cvzone img = cv.imread("image_path") # 获取图像高度、宽度 h, w = img.shape[:2] myColorFinder = ColorFinder(False) hsvValsOrange = {'hmin': 0, 'smin': 164, 'vmin': 0, 'hmax': 179, 'smax': 255, 'vmax': 255} imgColor,mask = myColorFinder.update(img,hsvValsOrange) imgContour, contours = cvzone.findContours(img,mask, minArea=1000) center_result = [] for cnt in contours: # 元组格式:(中心点x坐标, 翻转y轴后的中心点y坐标, 块面积) point_data = ( cnt["center"][0], h - cnt["center"][1], int(cnt["area"]) ) center_result.append(point_data) print(center_result) imgStack = cvzone.stackImages([img,imgColor,mask,imgContour],2,0.5) cv.imshow("Image", imgStack) cv.waitKey(0) cv.destroyAllWindows()
运行后center_result就是需要的元组列表,cvzone.findContours返回的contours已经按minArea=1000做了面积过滤,不会包含过小的噪点轮廓。
内容的提问来源于stack exchange,提问作者noca951
相关产品推荐
相关产品推荐

