HTPranav07
HTPranav07

Reputation: 11

Save the edge detected frames from a video as a video (opencv)

I Want to save the edge detected frames as a video. I am able to preview the frames of the video but the output video doesn't play.

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

fourcc = cv2.VideoWriter_fourcc(*'MP4V')

out = cv2.VideoWriter('output.mp4', fourcc, 23.976, (1280,720))

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

cap.release()
out.release()

Upvotes: 1

Views: 910

Answers (1)

Ahx
Ahx

Reputation: 7985

There are three issues I would like to address.

    1. You are applying Canny to each video frame. What is the output size:

      • print(edges.shape)
        (720, 1280)
        
      • The dimension 720, 1280 means the frame is a gray-scale value. If the frame is a color image then the dimension will be (720, 1080, 3) for each channel R, G, B.

      • Therefore you need to initialize your VideoWriter object as a grey-scale images.

      • out = cv2.VideoWriter('output.mp4', fourcc, 23.976, (1280,720), isColor=False)
        
    1. Make sure you are capturing the next frame:

      • ret, frame = cap.read()
        if ret:
            edges = cv.Canny(frame,50,50)
            .
            .
        
    1. Make sure your frame are the same dimension with the VideoWriter object
    • while cap.isOpened():
      ret, frame = cap.read()
      if ret:
          edges = cv2.Canny(frame, 50, 50)
          edges = cv2.resize(edges, (1280, 720))
          out.write(edges)
          .
          .
      

Code:


import cv2

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

fourcc = cv2.VideoWriter_fourcc(*"mp4v")

out = cv2.VideoWriter('output.mp4', fourcc, 23.976, (1280, 720), isColor=False)

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        edges = cv2.Canny(frame, 50, 50)
        edges = cv2.resize(edges, (1280, 720))
        out.write(edges)
        cv2.imshow('frame', edges)
        c = cv2.waitKey(1)
        if c & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
out.release()

Upvotes: 3

Related Questions