Webcam can not show picture with OpenCV in python 3.7

大憨熊 提交于 2019-12-11 06:47:36

问题


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 solution?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/56580450/webcam-can-not-show-picture-with-opencv-in-python-3-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!