使用OpenCV和Python显示摄像头源

我一直在试图用Python创build一个简单的程序,它使用OpenCV从我的networking摄像头获取video源,并将其显示在屏幕上。

我知道我有一部分是因为窗户被创造出来的,而且我的摄像头上的灯光在闪动,但它似乎并没有在窗户上显示任何东西。 希望有人能解释我做错了什么。

import cv cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE) capture = cv.CaptureFromCAM(0) def repeat(): frame = cv.QueryFrame(capture) cv.ShowImage("w1", frame) while True: repeat() 

在一个不相关的说明,我已经注意到,我的摄像头有时会改变它的索引号在cv.CaptureFromCAM ,有时我需要把0,1或2,即使我只有一个摄像头连接,我没有拔掉它(我知道是因为光线不会来,除非我改变指数)。 有没有办法让Python来确定正确的索引?

尝试在repeat()方法的底部添加c = cv.WaitKey(10)行。

这等待用户input密钥10毫秒。 即使你根本没有使用这个密钥,也要把它放进去。我认为这只是需要一些延迟,所以time.sleep(10)也可以工作。

关于相机索引,你可以做这样的事情:

 for i in range(3): capture = cv.CaptureFromCAM(i) if capture: break 

这将find第一个“工作”捕获设备的索引,至less对于0-2的索引。 计算机中有多个设备可能被识别为正确的捕获设备。 我知道的唯一方法是确认你是否有正确的方法是手动查看你的灯光。 也许得到一个图像,并检查其属性?

要向用户提示添加用户提示,可以在重复循环中绑定一个键以切换摄像机:

 import cv cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE) camera_index = 0 capture = cv.CaptureFromCAM(camera_index) def repeat(): global capture #declare as globals since we are assigning to them now global camera_index frame = cv.QueryFrame(capture) cv.ShowImage("w1", frame) c = cv.WaitKey(10) if(c=="n"): #in "n" key is pressed while the popup window is in focus camera_index += 1 #try the next camera index capture = cv.CaptureFromCAM(camera_index) if not capture: #if the next camera index didn't work, reset to 0. camera_index = 0 capture = cv.CaptureFromCAM(camera_index) while True: repeat() 

免责声明:我没有testing过,所以它可能有错误或只是不工作,但可能会给你至less一个解决方法的想法。

显示如何在最新版本的OpenCV中进行更新的更新:

 import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: cv2.imshow("preview", frame) rval, frame = vc.read() key = cv2.waitKey(20) if key == 27: # exit on ESC break cv2.destroyWindow("preview") vc.release() 

它适用于OpenCV-2.4.2。

如果您只有一个摄像头,或者您不在乎哪个摄像头是正确的,则使用“-1”作为索引。 即你的例子capture = cv.CaptureFromCAM(-1)

尝试以下。 这很简单,但我还没有想出一个优雅的方式退出。

 import cv2.cv as cv import time cv.NamedWindow("camera", 0) capture = cv.CaptureFromCAM(0) while True: img = cv.QueryFrame(capture) cv.ShowImage("camera", img) if cv.WaitKey(10) == 27: break cv.DestroyAllWindows() 

更改import cv import cv2.cv as cv另请参阅这里的post。

正如在opencv文档中,您可以通过以下代码从连接到计算机的相机获取video。

 import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() 

您可以将cap = cv2.VideoCapture(0)索引从0更改为1以访问第2台摄像机。
opencv-3.2.0testing