python opencv: cannot capture a window - python

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

Related

How to capture a 500 images from a video through webcam in opencv python?

I'm using the below code to capture images from webcam. But i need only some no.of images to be captured on click.
# Opens the inbuilt camera of laptop to capture video.
cap = cv2.VideoCapture(0)
i = 0
while(cap.isOpened()):
ret, frame = cap.read()
# This condition prevents from infinite looping
# incase video ends.
if ret == False:
break
# Save Frame by Frame into disk using imwrite method
cv2.imwrite('Frame'+str(i)+'.jpg', frame)
i += 1
cap.release()
cv2.destroyAllWindows()```
Assuming you want 500 images add this:
...
i+=1
if (i+1)%500==0:
break
that would be easy. you can use k = cv2.waitKey(1) and check what button was pressed. here is a simple example:
import cv2
def main():
cap = cv2.VideoCapture(0)
if not cap.isOpened(): # Check if the web cam is opened correctly
print("failed to open cam")
return -1
else:
print('webcam open')
for i in range(10 ** 10):
success, cv_frame = cap.read()
if not success:
print('failed to capture frame on iter {}'.format(i))
break
cv2.imshow('click t to save image and q to finish', cv_frame)
k = cv2.waitKey(1)
if k == ord('q'):
print('q was pressed - finishing...')
break
elif k == ord('t'):
print('t was pressed - saving image {}...'.format(i))
image_path = 'Frame_{}.jpg'.format(i) # i recommend a folder and not to save locally to avoid the mess
cv2.imwrite(image_path, cv_frame)
cap.release()
cv2.destroyAllWindows()
return
if __name__ == '__main__':
main()

Making a sequential playlist of videos in python

I'm trying to run a visual behaviour experiment where a whole heap of videos in a folder play one after another. I need to do this in python because I have a TTL pulse generator which I need to run at the start and end of each video.
I'm using cv2 and to try and play the videos but for reasons I can't figure out, I can't get them to play sequentially
Attached is my code
import cv2
import os
import random
videofolderPath = '/folderwithfiles'
videos = []
playlist = []
for file in os.listdir(videofolderPath):
if file.lower().endswith(".mp4"):
path=os.path.join('/folderwithfiles/',file)
playlist.append(path)
random.shuffle(playlist)
for i in range (3):
i += 1
cap = cv2.VideoCapture(playlist[i])
print(playlist[i])
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q') or ret==False :
cap.release()
cv2.destroyAllWindows()
break
cv2.imshow('frame',frame)
cap.release()
cv2.destroyAllWindows()
The issue I'm having is I think they're all playing at once. When I press q I do see another video behind it but am struggling to get them to play one after another.
It looks like you have an error because you try to show the video before testing if ret == False.
Also, you should update i at the end of the loop as python indexing is zero based
The fix would look like this: (note that I changed the video folder path to test your code)
import cv2
import os
import random
videofolderPath = './videos'
videos = []
playlist = []
for file in os.listdir(videofolderPath):
if file.lower().endswith(".mp4"):
path = os.path.join(videofolderPath, file)
playlist.append(path)
random.shuffle(playlist)
for i in range(3):
cap = cv2.VideoCapture(playlist[i])
print(playlist[i])
while True:
ret, frame = cap.read()
# REMOVE cv2.imshow(f'frame_{i}', frame)
if cv2.waitKey(1) & 0xFF == ord('q') or ret == False:
cap.release()
cv2.destroyAllWindows()
break
cv2.imshow('frame', frame)
cap.release()
cv2.destroyAllWindows()
i += 1 # UPDATE INDEX AT THE END
A better way of writing your code would be something like this:
import cv2
import os
if __name__ == '__main__':
video_folder = "./videos"
for video_name in os.listdir(video_folder):
if not video_name.endswith(".mp4"):
continue
video_path = os.path.join(video_folder, video_name)
video = cv2.VideoCapture(video_path)
while True:
ret, frame = video.read()
if not ret:
break
cv2.imshow("video", frame)
cv2.waitKey(1)
video.release()
cv2.destroyAllWindows()
Also, I would recommend you to look at threading to load your video in "parallel" as it is very cpu intensive

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

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

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

Categories

Resources