python对视频画框标记后保存

参考链接: 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

<think>好的,用户想用Python进行目标检测后对视频或图像进行重绘。我需要先理解他的需求。目标检测后的重绘可能指的是在检测到物体后,用方框标记出来,或者进行一些图像处理,比如缩放、裁剪等。首先,我得整理出目标检测和图像处理的基本步骤。 用户提到的参考引用中有关于图像缩放、Pillow和matplotlib绘图,以及模型压缩的内容。可能用户需要的是检测后的可视化部分。比如,使用OpenCV或Pillow来绘制检测框,然后保存或显示处理后的图像或视频。 首先,处理图像的话,可能需要用OpenCV读取图片,进行目标检测,然后用cv2.rectangle画框,再保存或显示。对于视频,可能需要逐帧处理,每一帧都进行检测和绘制,然后重新组合成视频。 另外,用户提到的引用[5]中有关于API设计的内容,可能涉及到保存标注信息,但用户的问题主要是重绘,所以重点可能在可视化部分。需要确保使用正确的库,比如OpenCV处理视频流,Pillow或matplotlib处理图像。 还需要考虑性能问题,尤其是视频处理,可能会比较耗时,需要优化代码,比如使用更高效的模型或减少处理帧率。此外,保存重绘后的视频需要注意编码格式和参数设置,避免出现问题。 用户可能不熟悉具体的代码实现步骤,所以需要分步骤说明,从安装库、读取数据、检测、绘制到保存结果。同时,提供示例代码会有帮助,比如用OpenCV和YOLO模型的简单示例,或者用Pillow绘制方框的方法。 可能还需要提醒用户注意路径问题,确保输入输出文件路径正确,以及依赖库的版本兼容性。比如,引用[2]中提到Pillow和matplotlib的版本,可能需要检查当前环境是否匹配。 总结一下,步骤大概是:1. 安装必要库;2. 加载模型进行检测;3. 处理图像或视频帧;4. 绘制检测结果;5. 保存或显示重绘后的文件。需要详细说明每个步骤,并提供代码示例,同时指出可能遇到的问题和优化方法。</think>以下是Python实现目标检测后对视频/图像进行重绘的方法详解: ### 一、基础流程 1. **目标检测**:使用YOLO、SSD等模型检测图像中的对象 2. **结果解析**:获取检测框坐标(xmin, ymin, xmax, ymax)和类别信息 3. **重绘处理**:根据坐标信息在原始图像上绘制方框和标签 4. **输出结果**:保存处理后的图像或重新编码视频流 ### 二、图像重绘示例(OpenCV) ```python import cv2 # 加载模型(示例使用OpenCV自带的DNN检测器) net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights') layer_names = net.getLayerNames() output_layers = [layer_names[i-1] for i in net.getUnconnectedOutLayers()] # 处理单张图像 def process_image(img_path): # 读取图像 img = cv2.imread(img_path) height, width = img.shape[:2] # 目标检测 blob = cv2.dnn.blobFromImage(img, 0.00392, (416,416), (0,0,0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # 绘制检测结果 for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: # 获取坐标 center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # 绘制矩形 cv2.rectangle(img, (center_x-w//2, center_y-h//2), (center_x+w//2, center_y+h//2), (0,255,0), 2) # 保存结果 cv2.imwrite('output.jpg', img) ``` ### 三、视频重绘关键点 ```python # 视频处理框架 cap = cv2.VideoCapture('input.mp4') fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4)))) while cap.isOpened(): ret, frame = cap.read() if not ret: break # 在此处插入目标检测代码(同上) # 处理后的frame添加检测框 out.write(frame) cap.release() out.release() ``` ### 四、优化建议 1. **模型选择**:轻量级模型如YOLOv5n/Tiny-YOLO更适合实时视频处理[^3] 2. **硬件加速**:使用CUDA加速(OpenCV DNN设置): ```python net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) ``` 3. **多线程处理**:分离视频捕获、检测、渲染线程提升效率 4. **图像缩放**:预处理时适当缩小输入尺寸加速检测[^1] ### 五、扩展应用 1. **语义分割重绘**:使用Mask R-CNN生成对象掩膜 2. **属性分析**:添加颜色直方图、纹理特征等附加信息[^4] 3. **标注保存**:将检测结果保存为YOLO格式标注文件[^5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值