以下是使用 OpenCV 进行黑色矩形识别并输出矩形的 4 个顶点坐标的代码示例:

import cv2
import numpy as np

def get_rectangle_vertices(contour):
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
    return approx.reshape(4, 2)

def detect_black_rectangle(image):
    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)
    
    for contour in contours:
        rect = cv2.minAreaRect(contour)
        box = cv2.boxPoints(rect).astype(np.int32)
        if cv2.contourArea(contour) > 2000 and len(box) == 4:
            vertices = get_rectangle_vertices(contour)
            return vertices
    
    return None

# 读取图像
image = cv2.imread('image.jpg')

# 检测黑色矩形
vertices = detect_black_rectangle(image)

if vertices is not None:
    # 绘制矩形
    cv2.drawContours(image, [vertices], -1, (0, 255, 0), 2)
    # 输出顶点坐标
    for vertex in vertices:
        x, y = vertex
        cv2.circle(image, (x, y), 5, (0, 0, 255), -1)

# 显示结果图像
cv2.imshow('Result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

请确保将代码中的 'image.jpg' 替换为您要处理的图像文件路径。这段代码首先将图像转换为灰度图像,然后通过二值化和轮廓检测找到所有的轮廓。接下来,通过计算最小外接矩形,筛选出面积大于 2000 的矩形轮廓。最后,绘制矩形并输出顶点坐标。

OpenCV 黑色矩形识别及顶点坐标获取代码示例

原文地址: https://www.cveoy.top/t/topic/fxxm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录