import cv2
import numpy as np

def detect_parallelograms(image):
    # 预处理图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

    # 查找轮廓
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    parallelograms = []
    for contour in contours:
        # 近似轮廓
        epsilon = 0.02 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)

        # 判断是否为四边形
        if len(approx) == 4:
            # 计算面积
            area = cv2.contourArea(approx)
            if area > 1000:  # 设置面积过滤阈值
                parallelograms.append(approx)

    return parallelograms

def get_coordinates(parallelogram):
    # 获取四个顶点的坐标
    vertices = []
    for vertex in parallelogram:
        x, y = vertex[0]
        vertices.append((x, y))

    # 计算中心点坐标
    center_x = int((vertices[0][0] + vertices[2][0]) / 2)
    center_y = int((vertices[0][1] + vertices[2][1]) / 2)
    center = (center_x, center_y)

    return vertices, center

def main():
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()

        parallelograms = detect_parallelograms(frame)

        for parallelogram in parallelograms:
            vertices, center = get_coordinates(parallelogram)

            # 绘制四边形
            cv2.drawContours(frame, [parallelogram], 0, (0, 255, 0), 2)

            # 在图像上标记顶点和中心点
            for vertex in vertices:
                cv2.circle(frame, vertex, 4, (0, 0, 255), -1)
            cv2.circle(frame, center, 4, (255, 0, 0), -1)

            # 输出顶点和中心点坐标
            for i, vertex in enumerate(vertices):
                print(f'Vertex {i+1}: {vertex[0]}, {vertex[1]}')
            print(f'Center: {center[0]}, {center[1]}')

        # 显示图像
        cv2.imshow('Parallelogram Detection', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

该代码使用 OpenCV 库检测视频流中的平行四边形,并输出其四个顶点坐标和中心点坐标。

代码功能:

  1. 预处理图像: 将图像转换为灰度图像,并使用 Otsu 阈值法进行二值化处理。
  2. 查找轮廓: 使用 cv2.findContours 函数查找图像中的轮廓。
  3. 识别平行四边形: 遍历所有轮廓,判断是否为四边形,并根据面积进行过滤。
  4. 获取顶点坐标: 获取平行四边形的四个顶点坐标。
  5. 计算中心点坐标: 计算平行四边形的中心点坐标。
  6. 绘制图形: 在图像上绘制平行四边形和顶点、中心点。
  7. 输出坐标: 将顶点坐标和中心点坐标输出到控制台。

代码运行步骤:

  1. 安装 OpenCV 库: pip install opencv-python
  2. 运行代码
  3. 使用键盘上的 'q' 键退出程序

输出结果:

代码会输出识别出的每个平行四边形的四个顶点坐标和中心点坐标,例如:

Vertex 1: x1, y1
Vertex 2: x2, y2
Vertex 3: x3, y3
Vertex 4: x4, y4
Center: xc, yc

其中 x1, y1; x2, y2; x3, y3; x4, y4 代表四个顶点的坐标,xc, yc 代表中心点坐标。

注意:

  • 代码默认使用摄像头作为输入视频源,您也可以修改 cv2.VideoCapture(0) 中的 0 为视频文件路径。
  • 面积过滤阈值 1000 可以根据实际情况进行调整。
  • 该代码仅供参考,您可以根据实际需求进行修改和扩展。
Python OpenCV 平行四边形检测及坐标输出

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

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