以下是代码实现:

import cv2

# 读入视频
cap = cv2.VideoCapture('C:/Users/Jionie/Desktop/dazuo/pp.mp4')

# 设置输出视频的参数
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

# 定义橙黄色的HSV范围
orange_lower = (10, 100, 100)
orange_upper = (20, 255, 255)

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        # 转换为HSV颜色空间
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # 生成橙黄色的遮罩
        mask = cv2.inRange(hsv, orange_lower, orange_upper)
        # 提取乒乓球的轮廓
        contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        # 如果存在轮廓,则提取乒乓球
        if len(contours) > 0:
            # 找到最大的轮廓
            max_contour = max(contours, key=cv2.contourArea)
            # 找到包围最大轮廓的最小圆形
            (x, y), radius = cv2.minEnclosingCircle(max_contour)
            center = (int(x), int(y))
            radius = int(radius)
            # 在黑色背景上绘制乒乓球的图像
            ball_img = cv2.bitwise_and(frame, frame, mask=mask)
            ball_img = ball_img[y - radius: y + radius, x - radius: x + radius]
            black_bg = np.zeros(frame.shape, dtype=np.uint8)
            black_bg[y - radius: y + radius, x - radius: x + radius] = ball_img
            # 将乒乓球的图像投屏到输出视频中
            out.write(black_bg)
        else:
            # 如果不存在轮廓,则直接将原始帧投屏到输出视频中
            out.write(frame)
    else:
        break

cap.release()
out.release()
cv2.destroyAllWindows()

运行以上代码后,会生成一个名为output.mp4的视频文件,其中只包含乒乓球的图像

写一段python代码运用mask处理技术用opencv 读入给定的乒乓mp4文件地址为CUsersJionieDesktopdazuoppmp4 编写代码分析每帧视频从视频画面中提取出一个乒乓球橙黄色圆形的遮罩然后再提取出乒乓球橙黄色圆形要求提取出的画面为以乒乓球橙黄色圆形的图像只包含乒乓球的图像投屏在一个黑色背景的视频中

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

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