参考链接: python-opencv-鼠标事件-画框圈定目标_Jason的博客-CSDN博客

# -*- coding: utf-8 -*-import cv2
import numpy as npcurrent_pos = None
tl = None
br = None#鼠标事件
def get_rect(im, title='get_rect'):   #   (a,b) = get_rect(im, title='get_rect')mouse_params = {'tl': None, 'br': None, 'current_pos': None,'released_once': False}cv2.namedWindow(title)cv2.moveWindow(title, 100, 100)def onMouse(event, x, y, flags, param):param['current_pos'] = (x, y)if param['tl'] is not None and not (flags & cv2.EVENT_FLAG_LBUTTON):param['released_once'] = Trueif flags & cv2.EVENT_FLAG_LBUTTON:if param['tl'] is None:param['tl'] = param['current_pos']elif param['released_once']:param['br'] = param['current_pos']cv2.setMouseCallback(title, onMouse, mouse_params)cv2.imshow(title, im)while mouse_params['br'] is None:im_draw = np.copy(im)if mouse_params['tl'] is not None:cv2.rectangle(im_draw, mouse_params['tl'],mouse_params['current_pos'], (255, 0, 0))cv2.imshow(title, im_draw)
#        _ = cv2.waitKey(10)cv2.waitKey(0)cv2.destroyWindow(title)tl = (min(mouse_params['tl'][0], mouse_params['br'][0]),min(mouse_params['tl'][1], mouse_params['br'][1]))br = (max(mouse_params['tl'][0], mouse_params['br'][0]),max(mouse_params['tl'][1], mouse_params['br'][1]))#返回矩形框坐标return (tl, br)  #tl=(y1,x1), br=(y2,x2)#读取摄像头/视频,然后用鼠标事件画框
def readVideo(pathName, skipFrame):  #pathName为视频文件路径,skipFrame为视频的第skipFrame帧
#    cap = cv2.VideoCapture(0)    #读取摄像头
#    if not cap.isOpened():  #如果未发现摄像头,则按照路径pathName读取视频文件
#        cap = cv2.VideoCapture(pathName)    #读取视频文件,如pathName='D:/test/test.mp4'cap = cv2.VideoCapture(pathName) #读取视频c = 1while(cap.isOpened()):ret, frame = cap.read()gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)if(c>=skipFrame):mask = np.zeros(gray.shape, dtype=np.uint8)  #掩码操作,该矩阵与图片大小类型一致,为初始化全0像素值,之后对其操作区域赋值为1即可if(c==skipFrame):(a,b) = get_rect(frame, title='get_rect')  #鼠标画矩形框img01, img02 = frame, framegray01, gray02 = gray, grayelse:img1, img2 = prev_frame, framegray1, gray2 = prev_frame, framecv2.imshow('frame', frame)c = c + 1prev_gray = grayprev_frame = frameif cv2.waitKey(1) & 0xFF == ord('q'):    #点击视频窗口,按q键退出breakcap.release()cv2.destroyAllWindows()video=readVideo("E:\\demo.mp4",1)----------
如果想要读取一张图片并手动画框(做目标跟踪时,经常需要第一帧的目标框),直接调用get_rect函数就可以啦~
img=cv2.imread("F:\\demo\\1.jpg")
(a,b)=get_rect(img,title='get_rect')
print(a,b)
cv2.destroyAllWindows()

需要画框取消注释rectangle

import cv2
import os,sys,shutil
import numpy as np
 
# Open the input movie file, input the filepath as
input_filepath = sys.argv[1]
input_movie = cv2.VideoCapture(input_filepath)
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
 
#设置output
output_movie = cv2.VideoWriter(input_filepath.replace("mp4","avi").replace("input","output"), cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'), 25, (1280, 720))
 
# Initialize some variables
frame_number = 0
 
while True:
    # Grab a single frame of video
    ret, frame = input_movie.read()
 
    frame_number += 1
 
    # Quit when the input video file ends
    if not ret:
        break
 
    # Draw a box around the body: input the top left point(x,y) and bottom right point(x,y)
    #cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
 
    # Write the resulting image to the output video file
    print("Writing frame {} / {}".format(frame_number, length))
    output_movie.write(frame)
 
# All done!
input_movie.release()
cv2.destroyAllWindows()
 
————————————————
版权声明:本文为CSDN博主「别说话写代码」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_21997625/article/details/82116778

pthon学习---opencv读取视频、保存视频和帧并画框_huanjin_w的博客-CSDN博客

opencv读取视频以及保存视频和帧并画框
仅打开监控、摄像头、视频代码
保存视频代码
保存帧(图片)代码
画框代码
效果
最后
仅打开监控、摄像头、视频代码
# TODO:单纯打开监控 或 本地摄像头 或 视频
import cv2
camera_path = "rtsp:..."  # 你的监控ip 
# camera_path = 0     # 本地摄像
# camera_path = 视频地址  如video.avi    video.mp4
cap = cv2.VideoCapture(camera_path)
while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) == ord('q'):
            break
1
2
3
4
5
6
7
8
9
10
11
12
保存视频代码
import cv2
'''无论是视频还是图片(视频帧)保存的地址后面都要加格式, 即视频的话就是.avi,.mp4等 图片就是.jpg, .png等'''
original_video_path = './data/video/child.avi'
new_video_path = './data/images/new_child.avi'

def new_video(path):
    cap = cv2.VideoCapture(path)  # 开启摄像头或者读取视频文件

# nframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))  # 计算出视频有多少帧,即后面保存图片就有多少张
    # print(nframes)
    fps = cap.get(cv2.CAP_PROP_FPS)  # FPS是每秒传输多少帧
    # print(fps)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    size = (w, h)  # 视频的宽和长
    # 视频写入 ,  第一个参数是视频保存的地址, 第二个参数是视频保存的格式, 第三个是保存的视频帧, 第四个是视频保存尺寸
    avi_write = cv2.VideoWriter(new_video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)

i = 0  # i是 0 -> nframes-1

while cap.isOpened():
        ret, frame = cap.read()  # 一帧一帧读取  ret返回的是True有帧 或者False 无帧

if ret:
            if cv2.waitKey(1) == ord('q'):
                break
            '''将读取到的帧(图片) 写入到avi_write'''
            avi_write.write(frame)
        else:
            break
        i += 1
    cap.release()
    avi_write.release()

new_video(original_video_path)

cv2框选视频保存图片
一、任务描述
二、代码
三、结果
一、任务描述
从一段视频中选出某一区域,摁s保存该区域图片

二、代码
videoName = r'浙江卫视:十二道锋味.mp4'
saveDir = './data/train/Zhejiang/'

import cv2

n = 0  # number of saved pictures
rectangle = []  # points of crop area

def onTrackbarSlide(pos):
    videoCapture.set(cv2.CAP_PROP_POS_MSEC, pos * 1000)

def onmouse(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        rectangle.append((x, y))
        if len(rectangle) > 2:
            rectangle.clear()
            cv2.destroyWindow('crop')

if __name__ == '__main__':
    cv2.namedWindow('winname')
    videoCapture = cv2.VideoCapture(videoName)

FPS = videoCapture.get(cv2.CAP_PROP_FPS)
    frameCount = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
    timeCount = int(frameCount / FPS)

cv2.createTrackbar('Position', 'winname', 0, timeCount, onTrackbarSlide)
    cv2.setMouseCallback('winname', onmouse)

while True:
        ret, frame = videoCapture.read()
        if ret is True:
            crop = frame
            if len(rectangle) == 2:
                crop = frame[rectangle[0][1]:rectangle[1][1], rectangle[0][0]:rectangle[1][0]]
                # cv2.rectangle(frame, rectangle[0], rectangle[1], (0, 0, 255), 2)#draw rectangle
                cv2.imshow('crop', crop)
            cv2.imshow('winname', frame)

current = int(videoCapture.get(cv2.CAP_PROP_POS_MSEC) / 1000)
            cv2.setTrackbarPos('Position', 'winname', current)  # renew the location of video

key = cv2.waitKey(25)
            if key & 0xFF == ord('q'):  # quit
                break
            elif key & 0xFF == ord('s'):  # save
                cv2.imwrite(saveDir + str(n) + '.jpg', crop)
                n += 1
                print('Saved {} pictures'.format(n))
        else:
            break

videoCapture.release()
    cv2.destroyAllWindows()
————————————————
版权声明:本文为CSDN博主「XerCis」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lly1122334/article/details/89933268

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
保存帧(图片)代码
import cv2
'''无论是视频还是图片(视频帧)保存的地址后面都要加格式, 即视频的话就是.avi,.mp4等 图片就是.jpg, .png等'''
original_video_path = './data/video/child.avi'

new_images_path = './data/images/child_{}.jpg'

def new_video(path):
    cap = cv2.VideoCapture(path)  # 开启摄像头或者读取视频文件

# nframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))  # 计算出视频有多少帧,即后面保存图片就有多少张
    # print(nframes)
    fps = cap.get(cv2.CAP_PROP_FPS)  # FPS是每秒传输多少帧
    # print(fps)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    size = (w, h)  # 视频的宽和长
    # 视频写入 ,  第一个参数是视频保存的地址, 第二个参数是视频保存的格式, 第三个是保存的视频帧, 第四个是视频保存尺寸
    avi_write = cv2.VideoWriter(new_video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)

i = 0  # i是 0 -> nframes-1

while cap.isOpened():
        ret, img = cap.read()  # 一帧一帧读取  ret返回的是True有图片 或者False 无图片

if ret:
            cv2.imwrite(new_images_path.format(i), img)  # 写成图片保存
        else:
            break
        i += 1
    cap.release()
    avi_write.release()

new_video(original_video_path)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
画框代码
import random
import cv2
'''无论是视频还是图片(视频帧)保存的地址后面都要加格式, 即视频的话就是.avi,.mp4等 图片就是.jpg, .png等'''
original_video_path = './data/video/child.avi'
new_video_path = './data/images/1.avi'
new_images_path = './data/images/child_{}.jpg'

'''假设这是预测结果'''
'''box=[左上角x, 左上角y, 右下角x, 右下角y, 置信度, 类别]'''
box = [50, 60, 200, 410, 0.99, 'person']
'''画框所需的颜色'''
color = [random.randint(0, 255) for _ in range(3)]

def new_video(path, box, color):
    cap = cv2.VideoCapture(path)

fps = cap.get(cv2.CAP_PROP_FPS)

w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    size = (w, h)

avi_write = cv2.VideoWriter(new_video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)

label = '{} {}'.format(box[-1], box[-2])

i = 0  # i是 0 -> nframes-1
    while cap.isOpened():
        ret, img = cap.read()  # 一帧一帧读取

if ret:
            fontscale = 2  # 字体大小
            '''框的左上角和右下角坐标'''
            c1, c2 = (box[0], box[1]), (box[2], box[3])
            cv2.rectangle(img, c1, c2, color, fontscale, cv2.LINE_AA)  # 画框

if label:
                font_thickness = max(fontscale - 1, 1)  # 字体粗度
                '''  获取文字的(宽,高) 0是第一个字体'''
                t_size = cv2.getTextSize(label, 0, fontScale=fontscale / 3, thickness=font_thickness)[0]
                '''放标签的框的右上角'''
                c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
                # ''' -1是填充满 filled,画出放标签的框 并填充'''
                cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)

'''图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细'''
                cv2.putText(img, label, (c1[0], c1[1] - 2), 0, fontscale / 3, [225, 255, 255], font_thickness,
                            lineType=cv2.LINE_AA)
                
            '''写入'''
            cv2.imwrite(new_images_path.format(i), img)
            avi_write.write(img)
            
        else:
            break
        i += 1
    cap.release()
    avi_write.release()

new_video(original_video_path, box, color)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
效果

最后
自己记录下学习过程而已。
————————————————
版权声明:本文为CSDN博主「huanjin_w」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/huanjin_w/article/details/111192052

python对视频画框标记后保存相关推荐

  1. python视频帧提取并保存_如何用python实现视频关键帧提取并保存为图片?

    展开全部 import cv2 vc = cv2.VideoCapture('Test.avi') #读入视频文件2113 c=1 if vc.isOpened(): #判断是否正常打开5261 rv ...

  2. python 读取文件并且修改后保存

    最近学习python 后开始写了一下小demo ,再接再厉.纯新手,喜欢的可以点点赞. 感觉这个方法有些笨, 希望大家能给点好的建议, 不仅限于python. 本文主要是用于读取手机里面的文件,进行读 ...

  3. Python OpenCV 视频的读取和保存

    1. 打开本地的摄像头,读取视频的每一帧 import cv2 # 1: connect camera via USB , 0: connect camera installed in your co ...

  4. python读视频文件_python读取和保存视频文件

    如何用python实现视频关键帧提取并保存为图片?也许你会觉得对小编多做一点事你会觉得你很爽,可是在小编看来这是不屑的 import cv2vc = cv2.VideoCapture('Test.av ...

  5. Python处理视频文件的实用姿势

    Python处理视频文件的实用姿势 感觉这辈子,最深情绵长的注视,都给了手机. 视频是目前最热门的领域之一. 各平台争先推出便捷工具,自带滤镜和玩法,普通人也能轻松制作精美视频. 也有不少团队实现了批 ...

  6. python画图视频_你能分享比较全面的Python视频教程吗?谢谢《用python画图教程视频》...

    python好学吗? python相对于C 来说确实是好学的多. python不需要特别关注类型,因此不需要花费太多的时间在变量类型上面.python的语法相比于C 来说,要简单的多. 如何用pyth ...

  7. 【python实现视频解帧并保存到文件夹】

    [python实现视频解帧并保存文件夹] 1.功能说明 2.代码实现 3.函数方法解析 ① os.getcwd() ② cv2.VideoCapture().get方法获取视频的相关参数 ③ cv2. ...

  8. 用Python编写录屏程序将播放的视频用截屏方法转换为多帧图像编辑后保存为GIF格式动图文件

    有时编写游戏后发博文,为使读者有一个直观的游戏效果,会把游戏运行动画转换GIF格式动图发到博文中.本文介绍如何用python PIL库ImageGrab.grab()函数截屏,编写录屏程序,将视频转换 ...

  9. python调用手机摄像头,并保存视频

    python调用手机摄像头,并保存视频 说明:手机端安装IP摄像头APP,并开启 代码如下: # -*- coding: utf-8 -*- """ Created on ...

最新文章

  1. 字节跳动总结的设计模式 PDF 火了,完整版开放下载!
  2. golang goroutine 退出方法
  3. HOG特征向量的代码 源代码改
  4. C#之获取mp3文件信息
  5. C#日期时间类型格式化大全集 C#DateTime 类型格式化大全集
  6. winform 的exe为什么移动之后不能使用_C++MyDock配置要求、所需运行库、常见问题 初次使用必看...
  7. Oracle 数据库 各种索引类型 简单介绍
  8. mysql 日志文件_mysql日志文件在哪
  9. Android 10.0 强制app横屏显示
  10. 【BZOJ4453】cys就是要拿英魂! 后缀数组+单调栈+set
  11. 碎片化NFT研究报告:COSONFT提高NFT流动性的探索和实践
  12. 步进电机主要技术参数
  13. 思科配置系统日志服务器配置,思科交换机路由器配置日志服务器脚本
  14. SQL Server基础操作(此随笔仅作为本人学习进度记录七 !--函数)
  15. java中flist cannot_cannot
  16. 存货计价方法——加权平均法
  17. 可积 连续 可微 可导关系
  18. (二)理解word2vec:实践篇
  19. R155附录5 Part A
  20. 如何通过IP地址来访问网站

热门文章

  1. linux内核链表使用例,linux内核链表的使用例子
  2. 如何估算代码量_如何估算焊锡膏的印刷量?
  3. php网页添加图片的代码,天天查询-PHP版的kindeditor编辑器加图片上传水印功能
  4. qt windows 静态编译_VS+QT工程配置问题
  5. 华盛顿多家博物馆因美政府停摆“闭门谢客”
  6. Hadoop2.6.5集群搭建
  7. 个人博客开发-01-nodeJs项目搭建
  8. 解决 java “错误:编码GBK 的不可映射字符”
  9. 是否能领先e步 浅析SSD中的eTLC和eMLC颗粒
  10. jquery总结01-基本概念和选择器