OpenCV error when trying to capture frame every seconds - python

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

Related

Opencv naming image captures

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)

Error: !_img.empty() in function 'imwrite'

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.

Why can't I capture with my webcam more than once with OpenCV in Python?

I tried to write a small Python program which would allow me to start the webcam and capture and save the image to a .png file:
import cv2
cap = cv2.VideoCapture(0)
for i in range(3):
ret, frame = cap.read()
cap.release()
if ret == True:
cv2.imwrite(str(i) + 'image.png', frame)
else:
print("Webcam not working")
print(ret)
but when I execute it it would only save the image once under 0image.png and then display this in the console:
Webcam not working
False
Webcam not working
False
What am I doing wrong?
The cap.release() functions helps you to free up your system , i.e. , the camera device resource, and if not done so , then it will raise errors like Device or resource busy if you try to create a new instance .
So , you need to remove the cap.release() from your loop and place it at the end of your program .
This should work .
import cv2
cap = cv2.VideoCapture(0)
for i in range(3):
ret, frame = cap.read()
if ret == True:
cv2.imwrite(str(i) + 'image.png', frame)
else:
print("Webcam not working")
print(ret)`
cap.release()

python opencv: cannot capture a window

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

error: (-215) size.width>0 && size.height>0 in function imshow

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.

Categories

Resources