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

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()

There are three issues I would like to address.
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)
Make sure you are capturing the next frame:
ret, frame = cap.read()
if ret:
edges = cv.Canny(frame,50,50)
.
.
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()

Related

Opencv Watermark Transparency and Brightness

I have a logo and I am trying to put this logo into my video. When I add the logo with below codes, logo couldnt be original color, it shows transparent. But I dont want to transparency I need to put original color format.
I get this output:
This is my code:
img_path = 'ap_logo.png'
logo = cv2.imread(img_path,cv2.IMREAD_UNCHANGED)
#
#
watermark = image_resize(logo, height=300)
watermark = cv2.cvtColor(watermark, cv2.COLOR_BGR2BGRA)
watermark_h, watermark_w, watermark_c = watermark.shape
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
frame_h, frame_w, frame_c = frame.shape
# # overlay with 4 channel BGR and Alpha
overlay = np.zeros((frame_h, frame_w, 4), dtype='uint8')
for i in range(0, watermark_h):
print(i)
for j in range(0, watermark_w):
if watermark[i, j][3] != 0:
h_offset = frame_h - watermark_h
w_offset = frame_w - watermark_w
overlay[h_offset + i, w_offset + j] = watermark[i, j]
while(True):
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
cv2.addWeighted(overlay, 0.25, frame, 1.0, 0, frame)
# Display the resulting frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
if ret:
cv2.imshow('Frame', frame)
out.write(frame) # file a ilgili frame yazılıyor
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything done, relase the capture
cap.release()
out.release() # saved
cv2.destroyAllWindows()

Video written through OpenCV on Raspberry Pi not running

I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code
import cv2
cap = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'')
out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480))
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF== ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The video file is created but I am not able to run that file. I also tried with different formats like 'XVID','MJPG','H264' but faced the same issue.
My opencv version is 4.3.038
There are two issues, I would like to address:
Issue #1: DIVX should be declared as:
fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
Issue #2:
You have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480)
frame = cv2.resize(frame, (640, 480))
But if you use it with DIVX you will have a warning:
OpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Instead of DIVX use mp4v for creating .mp4 videos.
Code:
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('output.mp4', fourcc, 25, (640, 480), isColor=True)
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (640, 480))
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
You can try this code. Works for me
import cv2
cap = cv2.VideoCapture(0)
video_speed = 15 #This frame rate works well on my case
video_name = 'output.avi'
writer = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc('M','J','P','G'),video_speed, (640,480))
while True:
ret , frame = cap.read()
if ret == True:
writer.writer(frame)
cv2.imshow('Frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
cap.release()
writer.release()
cv2.destroyAllWindows()

How to solve Opencv VideoWriter issues with global variables

I'mm writing this piece of python to display a stream of video from my webcam while at the same time record the video - which I've got working, however I've grayscaled the video streaming to my screen and time stamped it - but my recorded video is in colour! I've included the code below - I've tried using some global variables but nothing worked - any help, greatly appreciated
import cv2
import numpy as np
import time, datetime
import os
genericfilename = "recording"
filetime = str(time.time())
extension = '.avi'
filename = genericfilename + filetime +extension
frames_per_second = 100
res = '720p'
print("NEW FILE NAME: " + filename)
# Set resolution for the video capture
def change_res(cap, width, height):
cap.set(3, width)
cap.set(4, height)
# Standard Video Dimensions Sizes
STD_DIMENSIONS = {
"480p": (640, 480),
"720p": (1280, 720),
"1080p": (1920, 1080),
"4k": (3840, 2160),
}
# grab resolution dimensions and set video capture to it.
def get_dims(cap, res='1080p'):
width, height = STD_DIMENSIONS["480p"]
if res in STD_DIMENSIONS:
width,height = STD_DIMENSIONS[res]
## change the current caputre device
## to the resulting resolution
change_res(cap, width, height)
return width, height
# Video Encoding, might require additional installs
VIDEO_TYPE = {
'avi': cv2.VideoWriter_fourcc(*'XVID'),
#'mp4': cv2.VideoWriter_fourcc(*'H264'),
'mp4': cv2.VideoWriter_fourcc(*'XVID'),
}
def get_video_type(filename):
filename, ext = os.path.splitext(filename)
if ext in VIDEO_TYPE:
return VIDEO_TYPE[ext]
return VIDEO_TYPE['avi']
capture = cv2.VideoCapture(0)
out = cv2.VideoWriter(filename, get_video_type(filename), 60,
get_dims(capture, res))
while(True):
ret, frame = capture.read()
out.write(frame)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
font = cv2.FONT_ITALIC = 1
cv2.putText(grayFrame, str(datetime.datetime.now()), (-330, 460), font, 3,
(200, 200, 200), 2, cv2.LINE_AA)
cv2.imshow('combilift output', grayFrame)
# Press Q on keyboard to exit
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if cv2.waitKey(1) & 0xFF == ord('r'):
print(datetime.datetime.now())
capture.release()
out.release()
cv2.destroyAllWindows()
You save the frame to video, then convert frame to gray.
out.write(frame)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
If you want your recorded video to be gray, maybe reverse the order of operations and save grayFrame?
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(grayFrame)
If you want to also save the texts, put the text before writing frame to output.
Lets take a look at ur code
out = cv2.VideoWriter(filename, get_video_type(filename), 60,
.....
while(True):
ret, frame = capture.read()
out.write(frame)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
You first save out then convert color
The correct sequence should be
out = cv2.VideoWriter(filename, get_video_type(filename), 60,
.....
while(True):
ret, frame = capture.read()
grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(grayFrame)
I don't have data to test. Just in case you experience some issue with channels. You can use opencv merge(grayFrame,grayFrame,grayFrame) to create a normal 3 channel grey scale image and save to video

Opencv Writing video as output.avi from video file not from webcam

I am trying to write a video from video file it's not working but when I am using webcam code it's working
there are 2 files one is file.py and the other is web.py
here is my file.py
import numpy as np
import cv2
cap = cv2.VideoCapture('People - 6387.mp4')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
and this is my webcam.py this is working properly and writing video
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()`

OpenCV MP4 Creation

I've been trying to trying to write MP4 video files using OpenCV, in python.
AVI creation works fine, both on linux and windows, when I use both:
out = cv2.VideoWriter('x.avi', 0, 30, (640, 480))
and
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x.avi', fourcc, 30, (640, 480))
and even
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x', fourcc, 30, (640, 480))
.
When I try to save an MP4 however nothing ever saves - using:
fourcc = cv2.VideoWriter_fourcc(*"H264")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))
and
fourcc = cv2.VideoWriter_fourcc(*"AVC1")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))
No errors occur, just nothing saves.
I've tried everything over the past few days, doing everything to avoid creating the AVI and then converting it to MP4 using ffmpeg as I find that to be horrible practice.
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))
while(True):
ret, frame = cap.read()
out.write(frame)
cv2.imshow('frame', frame)
c = cv2.waitKey(1)
if c & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
Give right values of the high and width of the frames:
import cv2
print ('Press [ESC] to quit demo')
# Read from the input video file
# input_file = 'Your path to input video file'
# camera = cv2.VideoCapture(input_file)
# Or read from your computer camera
camera = cv2.VideoCapture(0)
# Output video file may be with another extension, but I didn't try
# output_file = 'Your path to output video file' + '.avi'
output_file = "out.avi"
# 4-byte code of the video codec may be another, but I did not try
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
is_begin = True
while camera.isOpened():
_, frame = camera.read()
if frame is None:
break
# Your code
processed = frame
if is_begin:
# Right values of high and width
h, w, _ = processed.shape
out = cv2.VideoWriter(output_file, fourcc, 30, (w, h), True)
print(out.isOpened()) # To check that you opened VideoWriter
is_begin = False
out.write(processed)
cv2.imshow('', processed)
choice = cv2.waitKey(1)
if choice == 27:
break
camera.release()
out.release()
cv2.destroyAllWindows()
This code works for me.

Categories