opencv检测黑色轮廓(矩形)

发布时间 2023-08-08 23:41:58作者: ihuahua1415

opencv检测黑色轮廓:

import cv2
import numpy as np

class ShapeDetector:
    def __init__(self, image_path):
        self.image_path = image_path
        self.img = cv2.imread(self.image_path)  # 读取图像
        self.imgContour = self.img.copy()  # 创建一个用于绘制轮廓的副本

    def detect_shapes(self):
        imgGray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)  # 转换为灰度图像
        imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1)  # 高斯模糊
        imgCanny = cv2.Canny(imgBlur, 60, 60)  # Canny边缘检测
        self.shape_detection(imgCanny)  # 进行形状检测

        # 显示图像
        cv2.imshow("原始图像", self.img)
        cv2.imshow("灰度图", imgGray)
        cv2.imshow("模糊图", imgBlur)
        cv2.imshow("边缘检测图", imgCanny)
        cv2.imshow("形状检测", self.imgContour)

        cv2.waitKey(0)
        cv2.destroyAllWindows()

    def shape_detection(self, img):
        contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # 寻找轮廓
        for obj in contours:
            area = cv2.contourArea(obj)  # 计算轮廓区域面积
            cv2.drawContours(self.imgContour, [obj], -1, (255, 0, 0), 4)  # 绘制轮廓线
            perimeter = cv2.arcLength(obj, True)  # 计算轮廓周长
            approx = cv2.approxPolyDP(obj, 0.02 * perimeter, True)  # 近似多边形
            corner_num = len(approx)  # 角点数量
            x, y, w, h = cv2.boundingRect(approx)  # 获取边界框坐标

            if corner_num == 3:
                obj_type = "三角形"
            elif corner_num == 4:
                for i in range(0, 4):
                    print("矩形角坐标%d:" % (i + 1), approx[i][0][0], approx[i][0][1])
                    cv2.circle(self.imgContour, (approx[i][0][0], approx[i][0][1]), 5, (0, 255, 255), 3)
                if w == h:
                    obj_type = "正方形"
                else:
                    obj_type = "矩形"
            elif corner_num > 4:
                obj_type = "多边形"
            else:
                obj_type = "未知"

            cv2.rectangle(self.imgContour, (x, y), (x + w, y + h), (0, 0, 255), 2)  # 绘制边界框
            cv2.putText(self.imgContour, obj_type, (x + (w // 2), y + (h // 2)), cv2.FONT_HERSHEY_COMPLEX, 0.6, (0, 0, 0), 1)

if __name__ == "__main__":
    image_path = './test.jpg'
    shape_detector = ShapeDetector(image_path)
    shape_detector.detect_shapes()