Python Opencv在视频上用鼠标画任意多边形

主要利用了opencv的鼠标回调函数:
1.点击鼠标左键,画出点
2.点击鼠标右键,生成闭合多边形,并输出坐标点。
3.点击鼠标中键,删除多边形。
4.按Q键,退出。
话不多说,直接上代码:

# -*- coding: utf-8 -*-
import cv2
import time
import numpy as np
tpPointsChoose = []
drawing = False
tempFlag = False
def draw_ROI(event, x, y, flags, param):
    global point1, tpPointsChoose,pts,drawing, tempFlag
    if event == cv2.EVENT_LBUTTONDOWN:
        tempFlag = True
        drawing = False
        point1 = (x, y)
        tpPointsChoose.append((x, y))  # 用于画点
    if event == cv2.EVENT_RBUTTONDOWN:
        tempFlag = True
        drawing = True
        pts = np.array([tpPointsChoose], np.int32)
        pts1 = tpPointsChoose[1:len(tpPointsChoose)]
        print(pts1)
    if event == cv2.EVENT_MBUTTONDOWN:
        tempFlag = False
        drawing = True
        tpPointsChoose = []
cv2.namedWindow('video')
cv2.setMouseCallback('video',draw_ROI)
cap = cv2.VideoCapture('1.avi')  # 文件名及格式
fps=cap.get(cv2.CAP_PROP_FPS)
size=(cap.get(cv2.CAP_PROP_FRAME_WIDTH),cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print("fps: {}\nsize: {}".format(fps,size))
vfps = 0.7/fps  #延迟播放用,根据运算能力调整
while (True):
    # capture frame-by-frame
    ret, frame = cap.read()
    # display the resulting frame
    if (tempFlag == True and drawing == False) :  # 鼠标点击
        cv2.circle(frame, point1, 5, (0, 255, 0), 2)
        for i in range(len(tpPointsChoose) - 1):
            cv2.line(frame, tpPointsChoose[i], tpPointsChoose[i + 1], (255, 0, 0), 2)
    if (tempFlag == True and drawing == True):  #鼠标右击
        cv2.polylines(frame, [pts], True, (0, 0, 255), thickness=2)
    if (tempFlag == False and drawing == True):  # 鼠标中键
        for i in range(len(tpPointsChoose) - 1):
            cv2.line(frame, tpPointsChoose[i], tpPointsChoose[i + 1], (0, 0, 255), 2)
    time.sleep(vfps)
    cv2.imshow('video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):  # 按q键退出
        break
# when everything done , release the capture
cap.release()
cv2.destroyAllWindows()
  • 9
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

greatsam

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值