python opencv 读取mp4,上一帧,下一帧

这篇具有很好参考价值的文章主要介绍了python opencv 读取mp4,上一帧,下一帧。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

安装pynput:

python opencv 读取mp4, 有上一帧,下一帧的功能

队列 缓存最新版,有帧号

队列封装成类版本:


安装pynput:

pip install pynput

python opencv 读取mp4, 有上一帧,下一帧的功能

这个每次读取self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index),后退读取稍微有点慢,文章来源地址https://www.toymoban.com/news/detail-733451.html

import cv2
from pynput import keyboard

class VideoPlayer:
    def __init__(self, video_path):
        self.cap = cv2.VideoCapture(video_path)
        self.frame_index = -1
        self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        self.new_frame_flag = False
        self.last_frame_i=0

    def show_frame(self, frame_index):
        if 0 <= frame_index < self.total_frames:
            if frame_index<self.last_frame_i:
                self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
            self.last_frame_i = frame_index
            ret, frame = self.cap.read()
            if ret:
                cv2.imshow('Video', frame)
                self.frame_index = frame_index
                self.new_frame_flag = False

    def next_frame(self):
        if self.frame_index + 1 < self.total_frames:
            self.frame_index += 1
            self.new_frame_flag = True

    def prev_frame(self):
        if self.frame_index - 1 >= 0:
            self.frame_index -= 1
            self.new_frame_flag = True

    def on_press(self, key):
        if key == keyboard.Key.right:  # Right arrow key
            self.next_frame()
        elif key == keyboard.Key.left:  # Left arrow key
            self.prev_frame()
        elif str(key) == "'q'":  # Press 'q' to exit
            return False

    def play(self):
        listener = keyboard.Listener(on_press=self.on_press)
        listener.start()

        self.show_frame(0)  # Show the first frame

        while True:
            if self.new_frame_flag:
                self.show_frame(self.frame_index)
            if cv2.waitKey(1) & 0xFF == ord('q'):  # Press 'q' to exit
                break

        cv2.destroyAllWindows()

if __name__ == "__main__":
    player = VideoPlayer(rf'F:\data\9.mp4')
    player.play()

队列 缓存最新版,有帧号

import cv2
from collections import deque
from pynput import keyboard


def on_press(key):
    global queue_index, load_new_frame
    if key == keyboard.Key.right or key == keyboard.Key.space:  # Right arrow key
        if queue_index < len(frame_buffer) - 1:
            queue_index += 1
        else:
            load_new_frame = True
    elif key == keyboard.Key.left:  # Left arrow key
        if queue_index > 0:
            queue_index -= 1
        load_new_frame = False
    elif str(key) == "'q'":  # Press 'q' to exit
        return False


listener = keyboard.Listener(on_press=on_press)
listener.start()

if __name__ == '__main__':
    cap = cv2.VideoCapture(r'C:\Users\Administrator\Documents\youjie\zhuanchang\11.mp4')

    deque_len = 300
    frame_buffer = deque(maxlen=deque_len)
    queue_index = -1
    load_new_frame = True
    frame_index = -1
    while cap.isOpened():
        if load_new_frame:
            ret, frame = cap.read()
            if not ret:
                print('video end')
                continue

            frame_index += 1
            cv2.putText(frame, str(frame_index), (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
            frame_buffer.append(frame)
            queue_index = len(frame_buffer) - 1
            # print('load frame_i', frame_index, "queue_i", queue_index, 'queue len', len(frame_buffer))
            load_new_frame = False

        # Show the current frame
        if len(frame_buffer) > 0:
            view_index = frame_index - len(frame_buffer) + queue_index + 1
            imshow = frame_buffer[queue_index]
            # print('show frame_i', frame_index, "queue_i", queue_index, 'view_i', view_index)
            if max(imshow.shape[:2])>1280:
                imshow = cv2.resize(imshow, (1280, 720))
            cv2.imshow('Video', imshow)

        if cv2.waitKey(1) & 0xFF == ord('q'):  # Press 'q' to exit
            break

    # Release the video and close windows
    cap.release()
    cv2.destroyAllWindows()

队列封装成类版本:

import glob
import os
import re

import cv2
from collections import deque

import yaml
from pynput import keyboard

from a2_jupter_check.ip_result.track_tool import get_box_dict, get_color

def show_box(track_id, box, black_image):
    color = get_color(box['sku'])
    cv2.rectangle(black_image, (box['box'][0], box['box'][1]), (box['box'][2], box['box'][3]), color, 1)
    cv2.putText(black_image, f"p:{(box['prob']):.3f}", (box['box'][0], box['box'][1] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
    cv2.putText(black_image, "t:" + str(track_id), (box['box'][0], box['box'][1] + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
    cv2.putText(black_image, "s:" + str(box['sku']), (box['box'][0], box['box'][1] + 60), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)


class VideoPlayer:
    def __init__(self, video_path,video_path2,track_txt):

        self.cap = cv2.VideoCapture(video_path)
        if door_type==1:
            self.cap2 = cv2.VideoCapture(video_path2)
        self.frame_index = -1
        self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        if door_type == 1:
            self.total_frames2 = int(self.cap2.get(cv2.CAP_PROP_FRAME_COUNT))
            self.total_frames=min(self.total_frames,self.total_frames2)

        self.top_dict,  self.bot_dict,  self.end_index = get_box_dict(track_txt)
        self.queue_index = -1
    def save_cls_err(self,cam_id):
        if cam_id==0:
            box_id=0
            for box in self.top_boxes:
                img_crop=self.top_image_o[box['box'][1]:box['box'][3],box['box'][0]:box['box'][2]]
                save_path=f"{cls_dir}/{box['sku']}_{(box['prob']):.2f}_{self.frame_index}_0_{box_id}.jpg"
                cv2.imwrite(save_path,img_crop)
                print('cls top save img',save_path)
                box_id+=1

        elif cam_id==1:
            box_id = 0
            for box in self.bot_boxes:
                img_crop = self.bot_image_o[box['box'][1]:box['box'][3], box['box'][0]:box['box'][2]]
                save_path=f"{cls_dir}/{box['sku']}_{(box['prob']):.2f}_{self.frame_index}_1_{box_id}.jpg"
                cv2.imwrite(save_path, img_crop)
                print('cls bot save img',save_path)
                box_id += 1
    def on_press(self, key):
        global box_offset
        if key == keyboard.Key.right or key == keyboard.Key.space:  # Right arrow key
            if self.queue_index < len(frame_buffer) - 1:
                self.queue_index += 1
            else:
                self.load_new_frame = True
        elif key == keyboard.Key.left:  # Left arrow key
            if self.queue_index > 0:
                self.queue_index -= 1
            self.load_new_frame = False
        elif key == keyboard.KeyCode.from_char('+'):  # Numpad +
            box_offset+=1
            print("box_offset +1", box_offset)
            self.new_frame_flag = True
        elif key == keyboard.KeyCode.from_char('-'):  # Numpad -
            box_offset-=1
            print("box_offset -1", box_offset)
            self.new_frame_flag = True

        elif hasattr(key, 'char') and key.char =='1':
            self.save_cls_err(0)
        elif hasattr(key, 'char') and key.char =='2':
            self.save_cls_err(1)
        elif hasattr(key, 'char') and key.char =='3':
            save_path = f"{det_dir}/{sw_name}_{self.frame_index}_0.jpg"
            cv2.imwrite(save_path, self.top_img_big)
            print('save det err cam 0', save_path)
        elif hasattr(key, 'char') and key.char =='4':
            save_path = f"{det_dir}/{sw_name}_{self.frame_index}_1.jpg"
            cv2.imwrite(save_path, self.bot_img_big)
            print('save det err cam 1',save_path)
        elif str(key) == "'c'":  # 's' key
            print('c')
        elif str(key) == "'d'":  # 's' key
            print('d')
        elif str(key) == "'q'":  # Press 'q' to exit
            return False
        else:
            try:
                if key.char == '/':  # 检查按键字符
                    print('Numpad / key pressed')
                elif key.char=='*':
                    print('Numpad * key pressed')
            except AttributeError:
                pass
    def show_frame(self):
        listener = keyboard.Listener(on_press=self.on_press)
        listener.start()
        self.load_new_frame = True
        while self.cap.isOpened():
            if self.load_new_frame:
                ret, frame = self.cap.read()
                if not ret:
                    print('video end')
                    continue

                self.frame_index += 1
                cv2.putText(frame, str(self.frame_index), (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
                frame_buffer.append(frame)
                self.queue_index = len(frame_buffer) - 1
                # print('load frame_i', self.frame_index, "queue_i", queue_index, 'queue len', len(frame_buffer))
                self.load_new_frame = False

            # Show the current frame
            if len(frame_buffer) > 0:
                view_index = self.frame_index - len(frame_buffer) + self.queue_index + 1
                imshow = frame_buffer[self.queue_index]
                # print('show frame_i', self.frame_index, "queue_i", queue_index, 'view_i', view_index)
                cv2.imshow('Video', imshow)

            if cv2.waitKey(1) & 0xFF == ord('q'):  # Press 'q' to exit
                break

        # Release the video and close windows
        self.cap.release()
        cv2.destroyAllWindows()
if __name__ == '__main__':

    sbbh='2212311106000040'

    dir_a= r'F:\data\jupiter\err_nos\0912\569'
    dir_a= r'D:\data\err_orders\jupter_pair_09\SW0031423091206302824557'
    dir_a= r'D:\data\err_orders\jupter_pair_09\SW0031423091206323752502'
    cooler_path = rf'F:\data\jupiter\configs/{sbbh}/config/config_cooler.yaml'

    with open(cooler_path, 'r') as file:
        yaml_dict = yaml.safe_load(file)
    img_x=yaml_dict['img_x']
    # img_x = 1920 - 1240 - img_x
    img_y=yaml_dict['img_y']
    top_line=yaml_dict['top_line']
    bot_line=yaml_dict['bot_line']
    img_height, img_width = 744, 1240
    door_type = 1

    cls_dir=dir_a+'/cls'
    det_dir=dir_a+'/det'
    os.makedirs(cls_dir,exist_ok=True)
    os.makedirs(det_dir,exist_ok=True)
    mp4_files = glob.glob(dir_a + '/high_*.mp4')
    # img_x=300+75
    # img_y= 202
    box_offset= 0
    video_path=video_path2=None
    for file in mp4_files:
        if "high_" in file and "_0_" in file:
            video_path=file
        elif "high_" in file and "_1_" in file:
            video_path2=file
        elif "high_" in file and "_2_" in file:
            video_path=file
            door_type = 2
            print("door_type=2")

    if door_type==1 and (video_path is None or video_path2 is None):
        print("cap1 or cap2 is None")
        exit(0)
    txt_path = video_path.replace(".mp4", "_tracks.txt")

    pattern = r'SW\d+'
    match = re.search(pattern, txt_path)
    sw_name = ""
    if match:
        sw_name = match.group()
    if door_type==2:
        img_x = 1920 - 1240 - img_x

    deque_len = 30
    frame_buffer = deque(maxlen=deque_len)


    save_width = 1000
    save_height = save_width *(img_height * 2)  // img_width
    mp4_path=os.path.dirname(txt_path)+'/'+sw_name+'_tracks.mp4'
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 或者使用 'X264'
    out_writer = cv2.VideoWriter(mp4_path, fourcc, 25.0, (save_width, save_height))
    print('save track mp4 ',mp4_path,'w',save_width,'h',save_height)
    player = VideoPlayer(video_path,video_path2, txt_path)
    player.show_frame()

到了这里,关于python opencv 读取mp4,上一帧,下一帧的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • javacv 基础04-读取mp4,avi等视频文件并截图保存图片到本地

    javacv 读取mp4,avi等视频文件并截图保存图片到本地 代码如下: 运行结果: 测试视频mp4 下载

    2024年02月11日
    浏览(61)
  • uni-app从后端返回的mp4链接视频截取一帧为封面

    一、需求: 后端返回包含视频链接的数组对象,格式如下: 从上面的mp4视频中截取一帧设置为封面,如下图,下面的封面图从视频中截取而来。 二、代码实现: 按照上面的代码,其中posterList就是对应的每一个视频的封面base64数组,一切看起来都挺好,在H5正常运行,但是在

    2024年02月14日
    浏览(47)
  • C#联合halcon读取上一张下一张图像

    namespace picture { public partial class Form1 : Form { public Form1 () { InitializeComponent(); } //获得文件夹中所有图片文件的全路径 string [] path = Directory.GetFiles( @“C:UsersynPicturesC#” ); int i = 0 ; //下一张 private void button2_Click ( object sender, EventArgs e) { //每点一下,i++,path[i]指向下一张图片 i++;

    2024年02月15日
    浏览(44)
  • 第4课 FFmpeg读取本地mp4文件并显示

    在上节课,我们使用FFmpeg实现了一个最简单的rtmp播放器,它看起来工作正常。这节课,我们尝试让它来播放本地的mp4文件试试。 1.压缩备份上节课工程文件夹为demo3.rar,并修改工程文件夹demo3为demo4,重要的事情再说一遍:及时备份源文件并在原基础上继续迭代开发是一种好

    2024年02月03日
    浏览(51)
  • android opencv 调用硬编码mediacodec保存mp4

    目录 c++ opencv部分 java 编码部分 Java jni声明: java调用: 获取类函数签名:

    2024年02月11日
    浏览(55)
  • OpenCV 报错:FFMPEG: tag 0x34363258/‘X264‘ is not supported with codec id 27 and format ‘mp4 / MP4‘

    首先说一下报错的地方,是在使用VideoWriter保存视频时: 出现如下错误: 经过查找网上资料,发现是cv2.VideoWriter_fourcc()参数存在问题, 解决方法: 将 修改为: 即可完美解决问题。

    2024年02月07日
    浏览(68)
  • python ts视频转mp4

    TS(TransportStream,传输流)是一种封装的格式,它的全称为MPEG2-TS。MPEG2-TS是一种标准数据容器格式,传输与存储音视频、节目与系统信息协议数据,主要应用于数字广播系统,譬如DVB、ATSC与IPTV。传输流最初是为广播而设计的。后来,通过在标准的188字节数据包中添加4字节的

    2024年02月07日
    浏览(51)
  • python统计mp4/avi视频的时长

    当代码中导入了特定的库,它会使得在代码中可以使用该库所提供的功能和工具。以下是导入的两个库及其作用的解释: os(Operating System)是Python标准库之一,提供了与操作系统交互的功能。它允许您在代码中执行各种与文件和目录操作相关的任务,例如创建、删除、移动文

    2024年02月14日
    浏览(55)
  • Python+OpenCV 零基础学习笔记(4-5):计算机图形基础+Python相对文件路径+OpenCV图像+OpenCV视频

    【2022B站最好的OpenCV课程推荐】OpenCV从入门到实战 全套课程 CSDN标题里个括号对应视频的分P OpenCV+Python CSDN专栏 Gitee 项目地址 Python:3.11.5 Anaconda:23.7.4 IDE:vscode 运行环境:Windows OpenCV:4.8.1 Python+OpenCV 零基础学习笔记(1-3):anaconda+vscode+jupyter环境配置 本节课来了解以下OpenCV的简单使用

    2024年02月03日
    浏览(79)
  • python学习之合并多张图片转成mp4视频代码实现

    随着现代科技飞速发展和人们提升视觉上体验,利用图片生成视频的方法,确实为工作或者提升生活体验感做了很多成功案例: 1、简单的幻灯片演示,如展示旅游照片、产品展示等; 2、改编图片动画,如口红试色、时尚大片中的效果; 3、制作日记式的视频内容,将一段长

    2023年04月21日
    浏览(73)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包