How to Save After Video File Edge Detection in opencv

Asked 2 years ago, Updated 2 years ago, 77 views

There is something I don't understand about how to use opencv.

I would like to have opencv detect the edge of the original video file and save it as a new video file.
Attempted to execute with the following code:

import numpy as np
import cv2

cap=cv2.VideoCapture('video.mp4')

fps = cap.get (cv2.CAP_PROP_FPS)
height=cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
width=cap.get(cv2.CAP_PROP_FRAME_WIDTH)

fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out=cv2.VideoWriter('output.mp4', int(fourcc), fps, (int(width), int(height)))

while(cap.isOpened()):
    try:
        ret, frame = cap.read()
        edge = cv2.Canny (frame, 50, 100)
        out.write(edge)
        cv2.imshow('frame',edge)
        if cv2.waitKey(1)&0xFF==ord('q'):
            break
    except:
        break

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

The video file is output, but the contents cannot be played.
Professor, please.

python opencv

2022-09-30 18:09

1 Answers

I was able to make a video by cutting out the images for each frame and connecting the images for each frame.
Please refer to the following.
Also, I used this video for edge processing.
Video used

import cv2
import glob
import re
importos

INPUT_FILE_NAME="airial.mp4"
OUTPUT_FILE_NAME="output.m4v"

# You can retrieve the image file path of the sorted serial number.
def numerical_sort(value):
    numbers = re.compile(r'(\d+)')
    parts=number.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts


def convert_video_2_images():
    # Loading Original Video Files
    org=cv2.VideoCapture(INPUT_FILE_NAME)
    i = 0
    if notos.path.exists("./images"):
        os.mkdir("./images")
    while org.isOpened():
        end_flag, frame = org.read()
        edge = cv2.Canny (frame, 100, 200)
        if not end_flag:
            break
        save_file="./images/img_{}.png".format(i)
        cv2.imwrite(save_file, edge)
        print("Save...{}.format(save_file))
        i+=1
    org.release()


def convert_images_2_video():
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    output = cv2.VideoWriter(OUTPUT_FILE_NAME,
                             fourcc,
                             30,
                             (1280, 720))

    for img_file in sorted(glob.glob("images/*.png"), key=numerical_sort):
        img=cv2.imread(img_file)
        output.write(img)
    output.release()

defmain():
    convert_video_2_images()
    convert_images_2_video()


if__name__=='__main__':
    main()


2022-09-30 18:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.