美文网首页
Matlab保存视频指定时间段的截图

Matlab保存视频指定时间段的截图

作者: 硅谷干货 | 来源:发表于2023-11-04 00:38 被阅读0次

    在测试和开发中,我经常遇到客户要求截取视频指定时间段的截图的需求,如果数据量大,就有点费手了,所有想到了使用自动化脚本来实现比较合适。下面我们以截取视频中第1秒到第8秒的视频截图来举例,看看如何来实现。

    Python 中的实现

    import cv2
    
    # 打开视频文件,并获取帧率
    cap = cv2.VideoCapture('./video/video.mp4')
    # fps = cap.get(cv2.CAP_PROP_FPS) # 30
    
    for count in range(1, 9):
        cap.set(cv2.CAP_PROP_POS_MSEC, 1.0 * 1000 * count)
        ret, frame = cap.read()
        if ret:
            cv2.imwrite(f'./video/{count}s.jpg', frame)  # 根据实际帧率可以调整
    
    

    Python批量改变截图尺寸

    from PIL import Image  
    import os  
      
    # 设定源文件夹路径  
    src_dir = '/path/to/your/source/folder'  
      
    # 设定目标文件夹路径  
    dst_dir = '/path/to/your/destination/folder'  
      
    # 设定新的图片尺寸,例如:宽度为800,高度为600  
    new_size = (800, 600)  
      
    # 遍历源文件夹中的所有文件  
    for filename in os.listdir(src_dir):  
        # 判断文件是否为图片文件(以.jpg或.png结尾)  
        if filename.endswith('.jpg') or filename.endswith('.png'):  
            # 获取图片的文件名和路径  
            filepath = os.path.join(src_dir, filename)  
            # 读取图片  
            img = Image.open(filepath)  
            # 修改图片大小尺寸  
            resized_img = img.resize(new_size, Image.ANTIALIAS)  
            # 设定新的图片文件名和路径  
            new_filepath = os.path.join(dst_dir, filename)  
            # 将修改后的图片保存到目标文件夹中  
            resized_img.save(new_filepath)
    

    Matlab 中的实现

    function captureAvis(startTime, endTime, avifilename, avipath, aviDirName)
      avifullpath = fullfile(avipath, avifilename);
      [~, aviname, ~] = fileparts(avifilename);
      videoReader = VideoReader(avifullpath);
      videoFPS = videoReader.FrameRate;
      for t = startTime: endTime
        if hasFrame(videoReader)
          videoReader.CurrentTime = t;
          imgName = sprintf('%s_%.1f.jpg', aviname(1:15), t);
          imwrite(frame, fullfile(aviDirName, imgName));
          disp(videoReader.CurrentTime);
          pause(1/videoFPS);
        end
    
        % if hasFrame(videoReader)
        %   videoFrame = read(VideoReader, t * round(videoFPS));
        %   imwrite(videoFrame, fullfile('saveas', strcat(t, '.jpg')));
        %   disp(t * videoFPS);
        % end
      end
    end
    
    

    Matlab批量修改截图尺寸

    function resizeImg(targetpath)
      if exist('targetpath')
        imgsDir = dir(targetpath);
      else
        imgsDir = dir(uigetdir(pwd, 'please select imgs dir'));
      end
      newSize = [1080, 1920];
      for i = 3: length(imgsDir)
        imgpath = fullfile(imgsDir(i).folder, imgsDir(i).name);
        originImg = imread(imgpath);
        resizedImg = imresize(originImg, newSize);
        imwrite(resizedImg, imgpath);
      end
    end
    

    不好意思,图片上传失败,吐槽一下,简书体验是真的垃圾~

    相关文章

      网友评论

          本文标题:Matlab保存视频指定时间段的截图

          本文链接:https://www.haomeiwen.com/subject/zlqaidtx.html