Home>

The process stops halfway,
The avi file is saved in the folder after processing, but it will be a video of about 2 seconds
What should I do if I want to continue taking a video and stop it?
Please give me advice.

  • Answer # 1

    Create a video file by performing edge processing in real time.
    The process flow is as follows

    1. Create a new folder directly under the current directory and move to that folder.
    2. Connect to web camera
    3.1 Load framesreal-timefor image processing
    4. Processed frames are displayed and saved as images (images are saved and stored for each frame)
    5. Repeat steps 3 and 4. Press the "esc" button to enter the termination process
    6. Create a video file from previously saved images

    import cv2
    import numpy as np
    import os
    import datetime
    ## Get current directory path
    current = os.getcwd ()
    ## Create directory
    now = datetime.datetime.now ()
    dir_name = "/IMG_{0:%m%d%H%M}".format(now)
    if os.path.isdir (current + dir_name) == False:
        os.mkdir (current + dir_name) #make directory
    os.chdir (current + dir_name) #move to directory
    # Create an instance of VideoCapture.
    cap = cv2.VideoCapture (0)
    cap.set (cv2.CAP_PROP_FPS, 30)
    #For frame count
    count = 1
    while True:
        # Load 1 frame from VideoCapture
        ret, frame = cap.read ()
        w, h = frame.shape [0], frame.shape [1]
        # Display unprocessed image
        cv2.imshow ('Raw Frame', frame)
        # Image processing
        gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)
        blur = cv2.GaussianBlur (gray, (11,11), 0)
        _, binary = cv2.threshold (blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
        nega = cv2.bitwise_not (binary)
        canny = cv2.Canny (nega, 100, 200)
        # Convert binary image to rgb
        backtorgb = cv2.cvtColor (canny, cv2.COLOR_GRAY2RGB)
        # Display processed image
        cv2.imshow ('Edited Frame', backtorgb)
        # Save frame
        filename = "IMG _ {}. jpg" .format (count)
        cv2.imwrite (filename, backtorgb)
        count + = 1
        # Wait 1ms for key input and break if k is 27 (ESC)
        k = cv2.waitKey (1)
        if k == 27:
            break
    # Release capture and close all windows
    cap.release ()
    cv2.destroyAllWindows ()
    # Create videos from sequential images
    fourcc = cv2.VideoWriter_fourcc ('m', 'p', '4', 'v')
    video = cv2.VideoWriter ('video.mp4', fourcc, 20.0, (h, w))
    for i in range (1, count):
        img = cv2.imread ("IMG _ {}. jpg" .format (i))
        img = cv2.resize (img, (h, w))
        video.write (img)
    video.release ()
    print ("Done")