OpenCV2 中识别特定尺寸矩形并提取坐标
您可以使用 OpenCV 中的 findContours 函数来找到图像中的轮廓,然后使用 boundingRect 函数来获取每个轮廓的边界框。最后,您可以根据边界框的宽高来筛选出宽高均大于 50 像素且小于 200 像素的矩形,并输出其四个顶点的坐标。\n\n下面是一个示例代码:\n\npython\nimport cv2\n\n# 读取图像\nimage = cv2.imread('image.jpg')\n\n# 将图像转换为灰度图\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# 二值化处理\nret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n\n# 寻找轮廓\ncontours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n# 遍历每个轮廓\nfor contour in contours:\n # 获取边界框\n x, y, w, h = cv2.boundingRect(contour)\n \n # 筛选出宽高均大于 50 像素且小于 200 像素的矩形\n if w > 50 and h > 50 and w < 200 and h < 200:\n # 输出矩形的四个顶点坐标\n print("Top Left: ({}, {})".format(x, y))\n print("Top Right: ({}, {})".format(x + w, y))\n print("Bottom Left: ({}, {})".format(x, y + h))\n print("Bottom Right: ({}, {})".format(x + w, y + h))\n\n\n请注意,这里假设您已经将图像保存在名为'image.jpg'的文件中。您可以根据实际情况修改代码中的图像路径。
原文地址: https://www.cveoy.top/t/topic/psOE 著作权归作者所有。请勿转载和采集!