I want to create frames from the video named project.avi and save them to frameIn folder. But some type of errors are not let me done. How can I solve this problem. Here is the code:
cap = cv2.VideoCapture('project.avi')
currentFrame = 0
while(True):
ret, frame = cap.read()
name = 'frameIn/frame' + str(currentFrame) + '.jpg'
print ("Creating file... " + name)
cv2.imwrite(name, frame)
frames.append(name)
currentFrame += 1
cap.release()
cv2.destroyAllWindows()
The error is:
Traceback (most recent call last):
File "videoreader.py", line 28, in <module>
cv2.imwrite(name, frame)
cv2.error: OpenCV(4.4.0) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-2rx9f0ng/opencv/modules/imgcodecs/src/loadsave.cpp:738: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
The cause may be that image is empty, so,
You should check weather video is opened correctly before read frames by: cap.isOpened().
Then, after execute ret, frame = cap.read() check ret variable value if true to ensure that frame is grabbed correctly.
The code to be Clear :
cap = cv2.VideoCapture('project.avi')
if cap.isOpened():
current_frame = 0
while True:
ret, frame = cap.read()
if ret:
name = f'frameIn/frame{current_frame}.jpg'
print(f"Creating file... {name}")
cv2.imwrite(name, frame)
frames.append(name)
current_frame += 1
cap.release()
cv2.destroyAllWindows()
I hope it helped you.
Related
I am trying to capture images from my cv2.imshow using the cv2.imwrite method, however I am getting an error when I try to use a function to constantly change the name of my capture. Does anybody know how to do this because I am getting an error.
My Code:
def imgcap():
vid = cv2.VideoCapture(0)
last_name = 9
def imgnames(last_name):
last_name = last_name + 1
return last_name
while True:
ret, frame = vid.read()
cv2.imshow('frame',frame)
cv2.imwrite('capture {last_name}', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
vid.release()
cv2.destroyAllWindows()
imgcap()
My Error:
cv2.imwrite('capture {last_name}', frame)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\imgcodecs\src\loadsave.cpp:682: error: (-2:Unspecified error) could not find a writer for the specified extension in function 'cv::imwrite_'
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\videoio\src\cap_msmf.cpp (434) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
I think you need to pick the extension for your new file? Please try one of the lines below!
cv2.imwrite('capture{last_name}.png', frame)
cv2.imwrite('capture{last_name}.jpg', frame)
I am trying to capture an image every 5 seconds in Opencv using my webcam however I am getting an error whenever I try.
Python Code:
def imgcap():
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
x=1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if ret:
# Our operations on the frame come here
filename = 'Captures/capture' + str(int(x)) + ".png"
x=x+1
cv2.imwrite(filename, frame)
time.sleep(5)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
print("Ret False")
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
imgcap()
imgcap()
Error I am Getting:
File "vision.py", line 30, in <module>
imgcap()
File "vision.py", line 21, in imgcap
cv2.imwrite(filename, frame)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\imgcodecs\src\loadsave.cpp:753: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'
The problem is you release the cap instance inside the loop. You wouldn't be able to read from cap from the 2nd iteration:
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# comment this
# cap.release()
# Our operations on the frame come here
filename = 'Captures/capture' + str(int(x)) + ".png"
#... other code
I am learning image processing using python and opencv
I write this code in python
import numpy as np
import cv2
vidCap=cv2.VideoCapture('output.avi')
print('before while')
while(vidCap.isOpened()):
print('inside while')
ret, frame=vidCap.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF==ord('q'):
break
print('outside while')
vidCap.release()
cv2.destroyWindow('LoadedVideo')
and it is giving me this error
Traceback (most recent call last):
File "D:\Python Image
Processing\FirstExercise\PlayingVideoFromFile.py", line 12, in <module>
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
error: C:\builds\master_PackSlaveAddon-win32-vc12-
static\opencv\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 ||
scn == 4 in function cv::ipp_cvtColor
The code is passing None as the frame to cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) and this is causing the exception.
You should check the return value of vidCap.read(); if it returns False as the first item in the tuple then there was no grabbed frame and you should not call cv2.cvtColor() on it because its value will be None.
vidCap.isOpened() will continue to return True even after all the frames have been consumed, so it should not be used as the condition in the while loop. The loop could be written as:
if vidCap.isOpened():
while True:
ret, frame = vidCap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
else:
break
vidCap.release()
Now the loop is exited when there are no more frames to grab from the file or a 'q' key press is detected.
Sorry I paste mirror parts at worng place, and as frame is null during mirror part, I made it into a comment while running
Looks like my cap.read() can't read anything
This is really a simple python code of opencv for just capturing a window and make webcamera work. But when I ran it, no window shown but no bugs shown either. How can I know what's wrong readily?
How can I know if the webcamera is 0 or sth else?
Why the mirror part doesn't work?
Could someone recommend me some good examples for opencv on python?
Thank you!!
import cv2
def capture_camera(mirror=True, size=None):
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
#if mirror is True:
#frame = frame[:,::-1]
if size is not None and len(size) == 200:
frame = cv2.resize(frame, size)
cv2.imshow('camera capture', frame)
k = cv2.waitKey(100)
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
capture_camera()
Your code is not executiong below if statement
if size is not None and len(size) == 200:
because size is tuple and len(size) will return 2 since you defined
size = (800,600)
2nd mistake : you were changing frame array before it is initialized.
first you need to get frame array which is returned by cap.read() then you can check if mirror is True if yes then reverse the array by frame = frame[:,::-1]
try this code :
import cv2
def capture_camera(mirror=True, size=None):
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if mirror is True:
frame = frame[:,::-1]
size = (800,600)
if size is not None:
frame = cv2.resize(frame, size)
cv2.imshow('camera capture', frame)
k = cv2.waitKey(100)
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
capture_camera()
Try this code. It works for me:
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('Webcam (close with q)' ,frame)
if(cv2.waitKey(1) & 0xFF == ord('q')):
break
cap.release()
cv2.destroyAllWindows()
BTW:
Your code throws an error:
Traceback (most recent call last):
File "C:/Python/Scripts/OpenCV/Scripts/so_test.py", line 21, in <module>
capture_camera()
File "C:/Python/Scripts/OpenCV/Scripts/so_test.py", line 7, in capture_camera
frame = frame[:,::-1]
UnboundLocalError: local variable 'frame' referenced before assignment
The program needs to read a video, do the counting of frames and then show in a window. The error occurs after the video ends.
How can i solve this?
Here is the source:
import tkMessageBox
import cv2
banner = cv2.imread('../data/banner.png')
video = cv2.VideoCapture('../data/pintado_real_crop.avi')
contadorDeFrames = True
contador = 0
cv2.imshow('Projeto Pacu', banner)
cv2.moveWindow('Projeto Pacu', 100,50)
while(contadorDeFrames == True):
contadorDeFrames, frame = video.read()
contador = contador + 1
cv2.imshow("Video", frame)
cv2.moveWindow('Video', 100, 178)
print"Frame: %d" %contador
k = cv2.waitKey(30) & 0xff
if k == 27:
break
tkMessageBox.showinfo("Frames contador: %d" %contador)
video.release()
cv2.destroyAllWindows()
Complete Error:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp, line 269
Traceback (most recent call last):
File "/home/vagner/PycharmProjects/TesteVideo/src/TestaVideo.py", line 20, in <module>
cv2.imshow("Video", frame)
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp:269: error: (-215) size.width>0 && size.height>0 in function imshow
I donĀ“t have an answer for the question but i can specify from where the error came and i have a workaround.
Like you see in my first example i tried to print a quit in the if statement and noticed that it doesnt get called. So i showed how much Frames the video had and let the if statement get called by the framenumbers. So the Error Disapear.
Example 1:
import numpy as np
import cv2
cap = cv2.VideoCapture('richtigcounter.mp4')
frames =1
while True:
ret, frame = cap.read()
print ("test")
cv2.imshow('frame',frame)
frames =frames + 1
print (frames)
if cv2.waitKey(1) & 0xFF == ord('q'):
print("Quit")
break
cap.release()
cv2.destroyWindow(cap)
Example 2:
import numpy as np
import cv2
import time
def Reinfall():
cap = cv2.VideoCapture('reinfallcounter.mp4')
frames =1
while True:
ret, frame = cap.read()
cv2.imshow('video', frame)
frames =frames + 1
print (frames)
cv2.waitKey(1)
if frames == 245:
print("Quit")
break
cap.release()
cv2.destroyAllWindows()
In your code, you are trying to print the null frame:
contadorDeFrames, frame = video.read()
contador = contador + 1
cv2.imshow("Video", frame)
when your code reads the frame which is last frame+1, the value will be null and you are trying to print that frame. So check whether the frame is null or not and print.