I'm using the OpenCV webcam example. Works great, but wondering, if it's possible to add a "camera reconnect function". When I unplug the camera, the code will crash. That's normal, but I would like to keep it running until I replug the camera again.
I tried "try: & except:" as you can see below. Now the python doesn't crash & when I unplug the camera, it will start printing "disconnected" to the console. However, when I reconnect the camera back, it would not start automatically, need to reset the program.
Thanks
import numpy as np
import cv2
cap = cv2.VideoCapture(2)
#cap = cv2.VideoCapture(1)
if cap.isOpened():
while(True):
try:
# Capture frame-by-frame
ret, im= cap.read()
# Display the resulting frame
cv2.imshow('frame', im)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except:
print('Disconnected')
else:
print("camera open failed")
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Related
in face recognition I write below code but I still have problem that USB webcam could not open in new window I try to put -1 and 1 and it dose not work
import cv2
cam = cv2.VideoCapture(0)
cv2.namedWindow("press space to take a photo", cv2.WINDOW_NORMAL)
cv2.resizeWindow("press space to take a photo", 500, 300)
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
cv2.imshow("press space to take a photo", frame)
error message
[ WARN:0] global /tmp/pip-wheel-qd18ncao/opencv-python/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): cant open camera by index
failed to grab frame
I use Ezviz studio to change my ip address (When i connect to ezviz studio, i must to import verification code). I change Ip address of camera to 192.168.100.6. But i can't connect to my camera with python
import numpy as np
import cv2
cap = cv2.VideoCapture()
cap.open("http://192.168.100.6:8000/1")
while(True):
ret, frame = cap.read()
cv2.imshow('Stream IP camera opencv',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
Use
video_capture = cv2.VideoCapture('rtsp://admin:SZGBZT#192.168.1.2/h264_stream')
where admin is always admin and the password SZGBZT is the verification code on your camera
I am trying to capture image in every 5 seconds using opencv through my laptop's built-in webcam. I am using time.sleep(5) for the required pause. In every run, the first image seems to be correctly saved but after that rest all the images are being saved as an unsupported format (when i am opening them). Also I am unable to break the loop by pressing 'q'.
Below is my code.
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
x=1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cap.release()
# Our operations on the frame come here
filename = 'C:/Users/shjohari/Desktop/Retail_AI/MySection/to_predict/image' + str(int(x)) + ".png"
x=x+1
cv2.imwrite(filename, frame)
time.sleep(5)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Any help is appreciated.
Just a small change, solved my issue.
I included the below code inside the loop :P
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
Background - I have python and required scripts installed on my desktop.
I am developing a face recognition WebApp.
It is working fine from Command Line but when I try to run it from localhost on wampserver, the webcam lights get on but no webcam window appears and the page starts loading for unlimited time.
Here is the code for data training
#!C:\Users\Gurminders\AppData\Local\Programs\Python\Python35-32\python.exe
import cv2
import os
def assure_path_exists(path):
dir = os.path.dirname(path)
if not os.path.exists(dir):
os.makedirs(dir)
# Start capturing video
vid_cam = cv2.VideoCapture(0)
# Detect object in video stream using Haarcascade Frontal Face
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# For each person, one face id
face_id = input('Please Enter Casual ID --> ')
# Initialize sample face image
count = 0
assure_path_exists("dataset/")
# Start looping
while(True):
# Capture video frame
_, image_frame = vid_cam.read()
# Convert frame to grayscale
gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY)
# Detect frames of different sizes, list of faces rectangles
faces = face_detector.detectMultiScale(gray, 1.3, 5)
# Loops for each faces
for (x,y,w,h) in faces:
# Crop the image frame into rectangle
cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2)
# Increment sample face image
count += 1
# Save the captured image into the datasets folder
cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
# Display the video frame, with bounded rectangle on the person's face
cv2.imshow('frame', image_frame)
# To stop taking video, press 'q' for at least 100ms
if cv2.waitKey(100) & 0xFF == ord('q'):
break
# If image taken reach 100, stop taking video
elif count>100:
break
# Stop video
vid_cam.release()
# Close all started windows
cv2.destroyAllWindows()
It works fine on command line but not from localhost on wampserver.
I solved this problem
I replaced
if cv2.waitKey(100) & 0xFF == ord('q'):
With
if cv2.waitKey(5000):
here 5000 are 5 seconds
I come from RDBMS background and just starting on python. below is a simple code i written to invoke my web cam via python
import cv2
vid = cv2.VideoCapture(0)
while vid == True:
print("Connected....");
if cv2.waitKey(0) : break
cv2.release();
but i am getting error
AttributeError: module 'cv2.cv2' has no attribute 'release'
while executing it. I am running this code using python3.5 and on linux 14.04 platform. I can see cv2 package installed via help("modules") list and it gets imported as well without error . however i dont see it in the interpreter list of pycharm. please help.
cv2.release() does not exist. I think what you are trying to do is vid.release()
cv2 is the opencv module and vid is the VideoCapture object. which is the one that you have to do the release.
UPDATE:
The code you have has several mistakes. Before I only addressed the one you asked, but lets go through all of them.
First one, the indentation is wrong, I guess maybe it is from copying the code.
Second one
while vid == True:
This is not the correct way to do it. You can use the vid.isOpened() function to see if it opened/connected to the webcam.
Third one, you do not need to use ; after the instructions.
Fourth one, this one is not an error, but something that is not necessary
if cv2.waitKey(0) : break
the if is not necessary, waitKey will return the key pressed as an ascii character, if you use a number other than 0 it will return 0 if no key was pressed. But with 0 it will wait for a key to be pressed "blocking" the current thread (in case you have more than one). However, it will not wait unless that you have a imshow window opened.
Now, the complete code with those changes that I wrote and that checks if the script can connect to a camera will be
import cv2
vid = cv2.VideoCapture(0)
if vid.isOpened():
print ("Connected....")
else:
print ("Not Connected....")
vid.release()
In a similar fashion you can display the video until a key is pressed:
import cv2
vid = cv2.VideoCapture(0)
if vid.isOpened():
print ("Connected....")
while True:
ret, frame = vid.read()
if ret:
cv2.imshow("image", frame)
else:
print ("Error aqcuiring the frame")
break
if cv2.waitKey(10) & 0xFF:
break
else:
print ("Not Connected....")
vid.release()
cv2.destroyAllWindows()
If something is not clear, feel free to ask :)
import cv2
import numpy
img = cv2.imread("lena.jpg", 1)
cv2.imshow("image", img)
cv2.waitKeyEx(0)
cv2.destroyAllWindows()