8

I am wondering to create a function which can crop a video in a certain frame and save it on my disk (OpenCV,moviepy,or something like that)

I am specifying my function with parameters as dimension of frame along with source and target name (location)

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)

Any suggestions and ideas are really helpful

rish_hyun
  • 451
  • 1
  • 7
  • 13

2 Answers2

14

Ok I think you want this,

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()
Lleims
  • 1,275
  • 12
  • 39
  • Thanks for helping but `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>0 && size.height>0 in function 'cv::imshow'` Well I encountered this `x,y,h,w = 215,665,1155-215,725-665`,Also is there any way to have original fps?? – rish_hyun May 11 '20 at 07:27
  • If you see my answer, I put you how to obtain the h_frame, w_frame, fps and frames – Lleims May 11 '20 at 07:30
  • 1
    Your problem is the sizes that are you writing, 725-665 = 60, this values has to be bigger than 665. When you crop, you pass coords, that start on the left-upper corner of your video and you need to "go" to the right(x-axis) and down(y-axis). – Lleims May 11 '20 at 07:33
  • Thanks buddy! Thanks for helping me out ,It's working , also could you please help me to figure out why my video runs so fast?? – rish_hyun May 11 '20 at 07:56
  • `crop_frame = frame[y:y+h, x:x+h]`Please change `x+h` to `x+w` – rish_hyun May 11 '20 at 08:00
  • 1
    Also buddy, can you update you code regarding percentage of video cropped while script run?? I want to crop whole video so should i remove `if 15 <= cnt <= 90:`?? – rish_hyun May 11 '20 at 08:04
  • Big fail! Edited! I edited before the `if-else`, yes just remove it and save the image all the time – Lleims May 11 '20 at 08:08
2

search ROI in opencv: Consider (0,0) as the top-left corner of the image with left-to-right as the x-direction and top-to-bottom as the y-direction. If we have (x1,y1) as the top-left and (x2,y2) as the bottom-right vertex of a ROI, we can use Numpy slicing to crop the image with:

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

and this is useful link for you: Link

see this python example code:

# 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')
Taher Fattahi
  • 951
  • 1
  • 6
  • 14