I use the following code copied from opencv website :
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
But the image is black with some white noise :
I am pretty sure the problems is not come from my webcam device because I use "camera" APP in Windows 10, the picture can display well.
The following is my python environment :
Python : 3.7.1
OpenCV : 4.1.0.25 (also tried 3.4.5.20)
OS : windows 10
Webcam : Logitech C525
----------------------------update--------------------------------
I use anaconda spyder to run the same code, it work perfectly!
The problems only shows up when I use jupyter notebook, any solutions?
Try this, you can use isOpened()
to ensure that you can connect to the camera.
from threading import Thread
import cv2, time
class VideoStreamWidget(object):
def __init__(self, src=0):
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
time.sleep(.01)
def show_frame(self):
# Display frames in main program
cv2.imshow('frame', self.frame)
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
cv2.destroyAllWindows()
exit(1)
if __name__ == '__main__':
video_stream_widget = VideoStreamWidget()
while True:
try:
video_stream_widget.show_frame()
except AttributeError:
pass
I've had the same issue with my webcams with spyder. What worked for me was to change from python 3.7 to python 3.6
-> conda install python=3.6
If you are using an external webcam then you have use cv2.VideoCapture(1) instead of cv2.VideoCapture(0).
Because here 0 represent internal webcam and 1 represent external webcam
import cv2
cap = cv2.VideoCapture(1)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.