参考链接: python-opencv-鼠标事件-画框圈定目标_Jason的博客-优快云博客
# -*- coding: utf-8 -*-
import cv2
import numpy as np
current_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'] = True
if 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 = 1
while(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, frame
gray01, gray02 = gray, gray
else:
img1, img2 = prev_frame, frame
gray1, gray2 = prev_frame, frame
cv2.imshow('frame', frame)
c = c + 1
prev_gray = gray
prev_frame = frame
if cv2.waitKey(1) & 0xFF == ord('q'): #点击视频窗口,按q键退出
break
cap.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()
————————————————
版权声明:本文为优快云博主「别说话写代码」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/qq_21997625/article/details/82116778
pthon学习---opencv读取视频、保存视频和帧并画框_huanjin_w的博客-优快云博客
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()
————————————————
版权声明:本文为优快云博主「XerCis」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/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
效果
最后
自己记录下学习过程而已。
————————————————
版权声明:本文为优快云博主「huanjin_w」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/huanjin_w/article/details/111192052