Opencv naming image captures - python

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)

Related

OpenCV error when trying to capture frame every seconds

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

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.

Access phone camera using opencv

I'm trying to connect my phone camera using IP webcam application but I get when error when I run the code.
Also, the URL keeps changing. Is there a method so that I don't need to change the URL every time?
This is the code I am using:
import cv2
cap = cv2.VideoCapture("http://192.168.43.1:8080/shot.jpg")
while True:
ret, frame = cap.read()
cv2.imshow("IPWebcam", cv2.resize(frame, (600, 400)))
if cv2.waitKey(20) & 0xFF == ord('q'):
break
And this is the error message I get when I run it:
Traceback (most recent call last):
File ".\phone_cam.py", line 15, in <module>
cv2.imshow("IPWebcam", cv2.resize(frame, (600, 400)))
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-9gpsewph\opencv\modules\imgproc\src\resize.cpp:3929: error:
(-215:Assertion failed) !ssize.empty() in function 'cv::resize'
This answer will not directly solve the issue, but it will allow you to detect the cause and it's a good practice when reading a video, image or from a camera. Always check if the value of ret is True because if it is not, it means there was a problem reading the data.
import cv2
cap = cv2.VideoCapture("http://192.168.43.1:8080/shot.jpg")
while True:
ret, frame = cap.read()
if ret:
cv2.imshow("IPWebcam", cv2.resize(frame, (600, 400)))
if cv2.waitKey(20) & 0xFF == ord('q'):
break
else:
print("cap.read() returned False")
If the code prints the message in the else statement, that means there is an issue with the link. Check if it is the correct one and whether you need to add a username and password or not.
import cv2
import urllib.request
import numpy as np
URL = "http://192.168.43.1:8080/shot.jpg"
while(True):
img_arr = np.array(
bytearray(urllib.request.urlopen(URL).read()), dtype=np.uint8)
frame = cv2.imdecode(img_arr, -1)
# Display the image
cv2.imshow('IPWebcam', cv2.resize(frame, (1100, 800)))
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cv2.release()
cv2.destroyAllWindows()

i am having an error while opening a video file in python (opencv)

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.

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

Categories

Resources