2024-05-14T16:51:42.png
chatgpt:
现在有两段程序,分别实现了手的识别和pwm输出。现在请根据这两段程序,编写一个程序,实现手在摄像头上半部分时pwm输出200,手在摄像头画面下半部分时pwm输出100.

from XEdu.hub import Workflow as wf
import cv2
from pyfirmata import Arduino, util
import time

# 初始化摄像头
cap = cv2.VideoCapture(0)
# 初始化手部检测模型
det = wf(task='det_hand')
hand = wf(task='pose_hand21')
# 初始化Arduino板
board = Arduino('COM4')  
# 获取PWM引脚
pin3 = board.get_pin('d:3:p')

def set_pwm(pin, value):
    board.digital[pin].write(value / 255.0)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    bboxs = det.inference(data=frame, thr=0.3)
    img = frame

    for i in bboxs:
        keypoints, img = hand.inference(data=frame, img_type='cv2', bbox=i)
        # 获取手部关键点的坐标
        x, y = keypoints[0][0], keypoints[0][1]
        # 获取摄像头画面的高度
        height = img.shape[0]
        # 根据手部位置计算PWM输出值
        if y <= height // 2:  # 上半部分
            pwm_value = 200
        else:  # 下半部分
            pwm_value = 100
        # 设置PWM输出
        set_pwm(3, pwm_value)

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

cap.release()
cv2.destroyAllWindows()

发表评论