【问题标题】:Crop a video in python在 python 中裁剪视频
【发布时间】:2024-01-01 23:40:01
【问题描述】:

我想创建一个可以在特定帧中裁剪视频并将其保存在我的磁盘上的功能 (OpenCV、moviepy 或类似的东西)

我正在使用参数作为框架尺寸以及源和目标名称(位置)来指定我的函数

def vid_crop(src,dest,l,t,r,b):
  # something
  # goes
  # here

left = 1    #any number (pixels)
top = 2     # ''''
right = 3   # ''''
bottom = 4  # ''''

vid_crop('myvideo.mp4','myvideo_edit.mp4',left,top,right,bottom)

任何建议和想法都很有帮助

【问题讨论】:

  • 你知道起始帧和结束帧吗?
  • 好吧,我正在为结束帧提供参数,我对起始帧一无所知。如果我不给出起始帧会重要吗?我的意思是没有开始框架就可以吗?
  • 你需要说什么时候开始保存哈哈
  • 好的,你是要裁剪一帧得到图片,还是要得到更小的视频?
  • 裁剪整个视频(所有帧),宽度和高度较小,而不是视频长度

标签: python opencv video-processing video-capture moviepy


【解决方案1】:

好的,我想你想要这个,

import numpy as np
import cv2

# Open the video
cap = cv2.VideoCapture('vid.mp4')

# Initialize frame counter
cnt = 0

# Some characteristics from the original video
w_frame, h_frame = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps, frames = cap.get(cv2.CAP_PROP_FPS), cap.get(cv2.CAP_PROP_FRAME_COUNT)

# Here you can define your croping values
x,y,h,w = 0,0,100,100

# output
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('result.avi', fourcc, fps, (w, h))


# Now we start
while(cap.isOpened()):
    ret, frame = cap.read()

    cnt += 1 # Counting frames

    # Avoid problems when video finish
    if ret==True:
        # Croping the frame
        crop_frame = frame[y:y+h, x:x+w]

        # Percentage
        xx = cnt *100/frames
        print(int(xx),'%')

        # Saving from the desired frames
        #if 15 <= cnt <= 90:
        #    out.write(crop_frame)

        # I see the answer now. Here you save all the video
        out.write(crop_frame)

        # Just to see the video in real time          
        cv2.imshow('frame',frame)
        cv2.imshow('croped',crop_frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break


cap.release()
out.release()
cv2.destroyAllWindows()

【讨论】:

  • 感谢cv2.imshow('croped',crop_frame) cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width&gt;0 &amp;&amp; size.height&gt;0 in function 'cv::imshow'的帮助,好吧我遇到了这个x,y,h,w = 215,665,1155-215,725-665,还有什么办法可以有原始的fps??
  • 如果你看到我的回答,我告诉你如何获取h_frame、w_frame、fps和frame
  • 你的问题是你写的尺寸,725-665 = 60,这个值必须大于665。当你裁剪时,你传递坐标,从左上角开始您的视频,您需要向右(x 轴)和向下(y 轴)“移动”。
  • 谢谢哥们!感谢您帮助我,它正在工作,还请您帮我弄清楚为什么我的视频运行速度如此之快??
  • 另外,伙计,您能否更新有关脚本运行时裁剪的视频百分比的代码?我想裁剪整个视频,所以我应该删除if 15 &lt;= cnt &lt;= 90:??
【解决方案2】:

opencv 中搜索 ROI: 将 (0,0) 视为图像的左上角,从左到右为 x 方向,从上到下为 y 方向。如果我们将 (x1,y1) 作为左上角和 (x2,y2) 作为 ROI 的右下角顶点,我们可以使用 Numpy 切片来裁剪图像:

ROI = image[y1:y2, x1:x2]

这是对您有用的链接:Link

查看此 python 示例代码:

# Python 2/3 compatibility
from __future__ import print_function
# Allows use of print like a function in Python 2.x

# Import OpenCV and Numpy modules
import numpy as np
import cv2


try:
    # Create a named window to display video output
    cv2.namedWindow('Watermark', cv2.WINDOW_NORMAL)
    # Load logo image
    dog = cv2.imread('Intel_Logo.png')
    # 
    rows,cols,channels = dog.shape
    # Convert the logo to grayscale
    dog_gray = cv2.cvtColor(dog,cv2.COLOR_BGR2GRAY)
    # Create a mask of the logo and its inverse mask
    ret, mask = cv2.threshold(dog_gray, 10, 255, cv2.THRESH_BINARY)
    mask_inv = cv2.bitwise_not(mask)
    # Now just extract the logo
    dog_fg = cv2.bitwise_and(dog,dog,mask = mask)
    # Initialize Default Video Web Camera for capture.
    webcam = cv2.VideoCapture(0)
    # Check if Camera initialized correctly
    success = webcam.isOpened()
    if success == False:
        print('Error: Camera could not be opened')
    else:
        print('Sucess: Grabbing the camera')
        webcam.set(cv2.CAP_PROP_FPS,30);
        webcam.set(cv2.CAP_PROP_FRAME_WIDTH,1024);
        webcam.set(cv2.CAP_PROP_FRAME_HEIGHT,768);

    while(True):
        # Read each frame in video stream
        ret, frame = webcam.read()
        # Perform operations on the video frames here
        # To put logo on top-left corner, create a Region of Interest (ROI)
        roi = frame[0:rows, 0:cols ] 
        # Now blackout the area of logo in ROI
        frm_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
        # Next add the logo to each video frame
        dst = cv2.add(frm_bg,dog_fg)
        frame[0:rows, 0:cols ] = dst
        # Overlay Text on the video frame with Exit instructions
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(frame, "Type q to Quit:",(50,700), font, 1,(255,255,255),2,cv2.LINE_AA)
        # Display the resulting frame
        # Display the resulting frame
        cv2.imshow('Watermark',frame)
        # Wait for exit key "q" to quit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release all resources used
    webcam.release()
    cv2.destroyAllWindows()

except cv2.error as e:
    print('Please correct OpenCV Error')

【讨论】:

  • 感谢您的回答,但我正在寻找裁剪保存在我的磁盘上的视频
  • 您可以将 webcam = cv2.VideoCapture(0) 设置为 cv2.VideoCapture("file.mp4") 以读取保存在磁盘上的视频
最近更新 更多