【问题标题】:OpenCV imshow function display black image in jupyter notebookOpenCV imshow函数在jupyter笔记本中显示黑色图像
【发布时间】:2019-06-13 12:24:58
【问题描述】:

我使用从 opencv 网站复制的以下代码:

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

但是图像是黑色的,带有一些白噪声:

我很确定问题不是来自我的网络摄像头设备,因为我在 Windows 10 中使用“相机”APP,图片可以很好地显示。

以下是我的python环境:

Python : 3.7.1
OpenCV :  4.1.0.25 (also tried 3.4.5.20)
OS : windows 10
Webcam : Logitech C525

--------------更新------ --------------

我使用 anaconda spyder 运行相同的代码,它运行良好!

问题只有在我使用 jupyter notebook 时才会出现,有什么解决办法吗?

【问题讨论】:

    标签: python opencv jupyter-notebook ipython webcam


    【解决方案1】:

    试试这个,你可以使用isOpened()来确保你可以连接到相机。

    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
    

    【讨论】:

    • 相机已连接。
    【解决方案2】:

    我在使用 spyder 的网络摄像头时遇到了同样的问题。 对我有用的是从 python 3.7 更改为 python 3.6

    -> conda install python=3.6

    【讨论】:

      【解决方案3】:

      如果您使用的是外部网络摄像头,那么您可以使用 cv2.VideoCapture(1) 而不是 cv2.VideoCapture(0)。

      因为这里 0 代表内部网络摄像头,1 代表外部网络摄像头

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

      【讨论】:

      • 我把 0 改成了 1,但是出现了错误: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'
      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多