以下是一个基于 OpenCV 进行人体动作识别的 Python 程序:

import cv2
import numpy as np

# 定义一些常量
THRESHOLD = 100
BLUR_SIZE = 10
MHI_DURATION = 1
MAX_TIME_DELTA = 0.5
MIN_TIME_DELTA = 0.05

# 创建一个背景模型
bg_model = cv2.BackgroundSubtractorMOG2()

# 创建一个运动历史图像
motion_history = np.zeros((480, 640), np.float32)

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

# 循环处理每一帧图像
while True:
    # 读取一帧图像
    ret, frame = capture.read()

    # 如果无法读取图像,退出循环
    if not ret:
        break

    # 将图像转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 进行背景减除
    fgmask = bg_model.apply(gray)

    # 对前景进行二值化处理
    thres = cv2.threshold(fgmask, THRESHOLD, 1, cv2.THRESH_BINARY)[1]

    # 对二值化图像进行模糊处理
    blur = cv2.blur(thres, (BLUR_SIZE, BLUR_SIZE))

    # 更新运动历史图像
    cv2.motempl.updateMotionHistory(blur, motion_history, MHI_DURATION)

    # 计算运动轮廓
    contours, _ = cv2.findContours(blur, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 对每个运动轮廓进行处理
    for c in contours:
        # 计算轮廓的运动状态
        x, y, w, h = cv2.boundingRect(c)
        area = cv2.contourArea(c)
        if area < 100:
            continue
        motion = cv2.calcMotionGradient(motion_history[y:y+h, x:x+w], MAX_TIME_DELTA, MIN_TIME_DELTA)
        if np.max(motion) < 1:
            continue

        # 绘制运动轮廓
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

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

    # 等待按键
    if cv2.waitKey(1) == ord('q'):
        break

# 释放摄像头并关闭窗口
capture.release()
cv2.destroyAllWindows()

这个程序使用了 OpenCV 中的背景减除、运动历史、运动梯度等技术,可以识别人体的运动轮廓,并在图像中绘制出来。需要注意的是,这个程序只能在有运动的情况下才能识别运动轮廓,如果没有运动,程序将无法识别任何轮廓。

基于 OpenCV 的 Python 人体动作识别程序

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

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