open cv 识别 黑色矩形 输出矩形的坐标
要使用OpenCV识别黑色矩形并输出矩形的坐标,可以按照以下步骤进行:
- 导入所需的库:
import cv2
import numpy as np
- 读取图像并进行预处理。这里假设图像名为
image.jpg:
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- 使用阈值化将图像转换为二值图像。这里将灰度图像转换为黑白图像,阈值可以根据实际情况进行调整:
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
- 查找轮廓并筛选出符合条件的矩形。这里假设黑色矩形的面积大于1000:
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rectangles = []
for contour in contours:
area = cv2.contourArea(contour)
if area > 1000:
x, y, w, h = cv2.boundingRect(contour)
rectangles.append((x, y, w, h))
- 输出矩形的坐标:
for rect in rectangles:
x, y, w, h = rect
print(f"矩形坐标:({x}, {y}), 宽度:{w}, 高度:{h}")
完整的代码如下:
import cv2
import numpy as np
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rectangles = []
for contour in contours:
area = cv2.contourArea(contour)
if area > 1000:
x, y, w, h = cv2.boundingRect(contour)
rectangles.append((x, y, w, h))
for rect in rectangles:
x, y, w, h = rect
print(f"矩形坐标:({x}, {y}), 宽度:{w}, 高度:{h}")
请确保图像中的黑色矩形与背景有明显的对比度,以便能够准确地进行识别。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/iurE 著作权归作者所有。请勿转载和采集!