Python程序:调用电脑摄像头识别摄像头中存在的物体的形状

import cv2
import numpy as np

# 定义一个函数来识别形状
def detect_shape(contour):
    # 计算轮廓的近似多边形
    epsilon = 0.04 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)

    # 根据多边形的边数判断形状
    if len(approx) == 3:
        return "Triangle"
    elif len(approx) == 4:
        # 判断是否是矩形或正方形
        x, y, w, h = cv2.boundingRect(approx)
        aspect_ratio = w / float(h)
        if 0.95 < aspect_ratio < 1.05:
            return "Square"
        else:
            return "Rectangle"
    elif len(approx) > 4:
        return "Circle"
    return "Unknown"

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
    # 读取一帧图像
    ret, frame = cap.read()
    if not ret:
        break

    # 转为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # 对图像进行模糊处理,减少噪声
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # 使用Canny边缘检测
    edges = cv2.Canny(blurred, 50, 150)

    # 找到轮廓
    contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 在原图上绘制轮廓和形状
    for contour in contours:
        if cv2.contourArea(contour) > 500:  # 忽略小轮廓
            # 获取形状名称
            shape_name = detect_shape(contour)
            
            # 获取轮廓的边界框
            x, y, w, h = cv2.boundingRect(contour)
            
            # 绘制轮廓和形状名称
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(frame, shape_name, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

    # 显示图像
    cv2.imshow("Shape Detection", frame)

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

# 释放摄像头
cap.release()
cv2.destroyAllWindows()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值