Converting video into frames by openCV - python

while converting video into frames , it does converted but it show this error
4 while success:
35 success, frame = cap.read()
---> 36 grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
37 if(success==False and frame==None):
38 pass
error: OpenCV(3.4.2) c:\miniconda3\conda-bld\opencv suite_1534379934306\work\modules\imgproc\src\color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'cv::CvtHelper<struct cv::Set<3,4,-1>,struct cv::Set<1,-1,-1>,struct cv::Set<0,2,5>,2>::CvtHelper'

Instead of using success variable twice, check whether the camera or video is opened:
while cap.isOpened():
Then get the read outputs.
ret, frame = cap.read()
If the frame is returned successfully, write it to the folder:
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite("output_frames/gray.png", gray)
Since you'll have multiple frames, you can use a counter to save each frame.
count = 0
while cap.isOpened():
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite("output_frames/gray_{}.png".format(count), gray)
count += 1
Full code:
import cv2
cap = cv2.VideoCapture("video.mp4")
count = 0
while cap.isOpened():
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite("output_frames/gray_{}.png".format(count), gray)
cv2.imshow("output", gray)
count += 1
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
cv2.destroyAllWindows()
cap.release()

Related

Capturing frame from webcam, it return only 1 frame in opencv cv2.VideoCapture()

I'm new to image processing.
I'm trying to build traffic light detection following one of papers in Python OpenCV.
But I got an error I can't understand.
Here is the code.
# TL_Detection.py
import cv2
import numpy as np
def Video():
try:
cap = cv2.VideoCapture(0)
# cap = cv2.VideoCapture('/home/aicar/Downloads/tf_test.mp4')
except:
print('no cam error')
return
# cap.set(3, 480)
# cap.set(4, 320)
frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
size = (frameWidth, frameHeight)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cnt = 0
# while cap.isOpened():
while True:
ret, frame = cap.read()
# if not cap.isOpened():
# cap.open('/home/aicar/Downloads/tf_test.mp4')
cv2.imshow('frame', frame)
print(ret, cnt)
if not ret:
print('no ret error')
break
cnt += 1
cap.release()
cv2.destroyAllWindows()
Video()
This code returns like the following.
True 0
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/aicar/opencv/opencv-3.4.0/modules/highgui/src/window.cpp, line 339
Traceback (most recent call last):
File "/home/aicar/codes_juyeong/TL_detection.py", line 53, in <module>
Video()
File "/home/aicar/codes_juyeong/TL_detection.py", line 33, in Video
cv2.imshow('frame', frame)
cv2.error: /home/aicar/opencv/opencv-3.4.0/modules/highgui/src/window.cpp:339: error: (-215) size.width>0 && size.height>0 in function imshow
Why can't it get frame after getting only the first frame ?
The webcam is connected correctly.
need your help. Thanks.
you release your cap too early, it's in the true loop. so get it out of this loop and you program will run without any problems.
To capture frame after frame try this piece of code:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
# while cap.isOpened():
while True:
ret, frame = cap.read()
# if not cap.isOpened():
# cap.open('/home/aicar/Downloads/tf_test.mp4')
cv2.imshow('frame', frame)
print(ret, cnt)
if not ret:
print('no ret error')
break
cnt += 1
# take it out of while loop
cap.release()
cv2.destroyAllWindows()

[OpenCV Videocapture]Why isn't ret reading?

The code shows correct image, but show error message after image 'frame' playback. so I couldn't get 'res' image
It just shows me 'No Object Files' error message.
Which part should I fix to make it work?
import cv2
import numpy as np
cap = cv2.VideoCapture('ObjectTrack.mp4')
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("No Object Files")
break
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_orange = np.array([100,200,200])
upper_orange = np.array([140,255,255])
mask_orange = cv2.inRange(hsv, lower_orange, upper_orange)
res = cv2.bitwise_and(frame,frame,mask = mask_orange)
cv2.imshow('frame',frame)
cv2.imshow('res',res)
if cv2.waitKey(50) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The reason behind your error is that the frame is None(Null). and your code enters into this if
if not ret:
print("No Object Files")
break
and then gets out of the while loop ( while cap.isOpened(): ... ).
Just change the indentation and also the if condition
like this:
while cap.isOpened():
ret, frame = cap.read()
if ret: # if frame is not None:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_orange = np.array([100, 200, 200])
upper_orange = np.array([140, 255, 255])
mask_orange = cv2.inRange(hsv, lower_orange, upper_orange)
res = cv2.bitwise_and(frame, frame, mask=mask_orange)
cv2.imshow('frame', frame)
cv2.imshow('res', res)
if cv2.waitKey(50) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The reason is further discussed here.

How can I change a single frame in a video using OpenCV?

I have a video that I built using OpenCV VideoWriter.
I want to change a specific frame with a different one.
Is there a way to do it without rebuilding the entire video?
I am changing the third frame by making all pixels to zeros.
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))
frame_number = -1
while(True):
frame_number += 1
ret, frame = cap.read()
if frame_number == 3: # if frame is the third frame than replace it with blank drame
change_frame_with = np.zeros_like(frame)
frame = change_frame_with
out.write(frame)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
If you do not want to go through all the frames again:
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))
frame_number = -1
while(True):
frame_number += 1
ret, frame = cap.read()
if frame_number == 3: # if frame is the third frame than replace it with blank drame
change_frame_with = np.zeros_like(frame)
frame = change_frame_with
out.write(frame)
break # add a break here
else:
out.write(frame)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
But the above solution will not write all the other frames after 3 to the whole new video
This might help you :)
import cv2 as cv
vid = cv.VideoCapture('input.mp4')
total_frames = last_frame_number = vid.get(cv.CAP_PROP_FRAME_COUNT)
fourcc = cv.VideoWriter_fourcc(*'avc1')
writer = cv.VideoWriter("output.mp4", apiPreference=0,fourcc=fourcc,fps=video_fps[0], frameSize=(width, height))
frame_number = -1
while(True):
frame_number += 1
vid.set(1,frame_number)
ret, frame = vid.read()
if not ret or frame_number >= last_frame_number: break
# check these two lines first
if frame_number == changeable_frame_number :
frame = new_img_to_be_inserted
writer.write(frame)
# frame = np.asarray(frame)
gray = cv.cvtColor(frame, cv.IMREAD_COLOR)
# cv.imshow('frame',gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
vid.release()
writer.release()
cv.destroyAllWindows()

Processing frame every second in opencv python

Here is the code for reading video file from webcam using opencv website. I just want to process the frame every second.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
How should I modify the code:
You should just make your process wait for one second before each read:
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
start_time = time.time()
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
time.sleep(1.0 - time.time() + start_time) # Sleep for 1 second minus elapsed time
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

frame difference using python

I'm trying to do frame difference this is my code below
import numpy as np
import cv2
current_frame =cv2.VideoCapture(0)
previous_frame=current_frame
while(current_frame.isOpened()):
current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
previous_frame_gray= cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY)
frame_diff=cv2.absdiff(current_frame_gray,previous_frame_gray)
cv2.imshow('frame diff ',frame_diff)
cv2.waitKey(1)
current_frame.copyto(previous_frame)
ret, current_frame = current_frame.read()
current_frame.release()
cv2.destroyAllWindows()
my problem is that I tried to create empty frame to save the first frame from current_frame
previous_frame=np.zeros(current_frame.shape,dtype=current_frame.dtype)
But I think it is not correct , then I tried to pass current_frame like this:
previous_frame=current_frame
Now I'm getting this error :
current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
TypeError: src is not a numpy array, neither a scalar
so what should I do for this ?
Thanks for help
You have mixed the VideoCapture object and the frame.
I've also made small changes in the frame copy and waitkey.
import cv2
cap = cv2.VideoCapture(0)
ret, current_frame = cap.read()
previous_frame = current_frame
while(cap.isOpened()):
current_frame_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
previous_frame_gray = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY)
frame_diff = cv2.absdiff(current_frame_gray,previous_frame_gray)
cv2.imshow('frame diff ',frame_diff)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
previous_frame = current_frame.copy()
ret, current_frame = cap.read()
cap.release()
cv2.destroyAllWindows()

Categories

Resources