import cv2

定义黄色范围的上下界

lower_yellow = (20, 100, 100) upper_yellow = (40, 255, 255)

读取视频文件

cap = cv2.VideoCapture('C:/Users/Jionie/Desktop/dazuo/pp.mp4')

循环遍历每一帧

while True: ret, frame = cap.read()

if not ret:
    break

# 转换颜色空间为HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

# 创建黄色掩膜
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)

# 对掩膜进行形态学操作,去除噪点
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# 获取黄色球体轮廓
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    # 获取轮廓的面积和周长
    area = cv2.contourArea(cnt)
    perimeter = cv2.arcLength(cnt, True)

    # 判断轮廓是否为圆形,并且面积和周长符合条件
    if len(cnt) >= 5:
        (x, y), radius = cv2.minEnclosingCircle(cnt)
        if area > 100 and perimeter > 100 and abs(1 - (area / (3.14 * radius * radius))) < 0.3:
            # 提取黄色球体
            ball = frame[int(y - radius):int(y + radius), int(x - radius):int(x + radius)]

            # 显示提取出的圆形图像
            cv2.imshow('Yellow Ball', ball)

# 显示原视频和掩膜
cv2.imshow('Video', frame)
cv2.imshow('Mask', mask)

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

释放资源

cap.release() cv2.destroyAllWindows(

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

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

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