import cv2 import numpy as np

def find_second_largest_rectangle(): cap = cv2.VideoCapture(0) # 打开摄像头 cap.set(3,640) cap.set(4,480) while True: ret, frame = cap.read() # 读取摄像头的帧 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 将帧转换为灰度图像 _, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 对灰度图像进行二值化处理

    contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # 寻找轮廓
    contours = sorted(contours, key=cv2.contourArea, reverse=True)  # 按轮廓面积排序

    if len(contours) > 1:
        second_largest_contour = contours[1]  # 获取第二大的轮廓
        x, y, w, h = cv2.boundingRect(second_largest_contour)  # 获取轮廓的外接矩形

        x1, y1 = x, y
        x2, y2 = x + w, y
        x3, y3 = x + w, y + h
        x4, y4 = x, y + h

        x_center = (x1 + x2) / 2
        y_center = (y1 + y3) / 2

        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)  # 在原始图像上绘制第二大矩形
        cv2.imshow('Second Largest Rectangle', frame)  # 显示带有矩形的图像
        print(f'x1: {x1}, y1: {y1}')
        print(f'x2: {x2}, y2: {y2}')
        print(f'x3: {x3}, y3: {y3}')
        print(f'x4: {x4}, y4: {y4}')

    if cv2.waitKey(1) & 0xFF == ord('q'):  # 按下 'q' 键退出循环
        break

cap.release()  # 释放摄像头
cv2.destroyAllWindows()  # 关闭所有窗口

find_second_largest_rectangle()

Python OpenCV: Find Second Largest Rectangle in Image

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

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