我正在尝试通过 opencv python VideoCapture 访问基本网络摄像头(Logitech c270)。但不幸的是,每次我运行该程序时,显示屏都会变黑。我知道相机可以工作,因为我可以通过他们的软件查看视频。我很清楚确保输入 waitkey(x),这样就不是问题了。我也有这个代码,以防索引发生变化:
for i in range(4):
capture = cv2.VideoCapture(i)
if not capture:
print "UNABLE TO CAPTURE CAMERA"
else:
print "taken camera from index: ", i
break
但是每次都返回0索引。问题不在于它找不到它,因为我有一部分代码告诉我相机是否能够检索帧,所以问题可能出在 read() 上。 最后,也许问题是我的等待键在代码中缩进了很多,可能有四个索引,以至于它无法每次都引用等待键。这是我涉及到的代码块。我是新人,所以我确信优化和技术非常糟糕。
class ColourTracker(object):
def __init__(self):
#cv2.namedWindow("ColourTrackerWindow", cv2.CV_WINDOW_AUTOSIZE)
self.scale_down = 4
self.start = time.time()
def run(self):
for i in range(4):
capture = cv2.VideoCapture(i)
if not capture:
print "UNABLE TO CAPTURE CAMERA"
else:
print "taken camera from index: ", i
break
...
while True:
marker = marker + 1
if marker % 100 == 0:
print marker
f, orig_img = capture.read()
if not f:
print "Not read"
break
orig_img = cv2.flip(orig_img, 1)
cv2.imshow('orgImage', orig_img)
...
largest_contour = None
for idx, contour in enumerate(contours):
area = cv2.contourArea(contour)
if area > max_area:
max_area = area
largest_contour = contour
if not largest_contour == None:
...
#create an array of coordinates
if marker % 10 == 0:
cycle = [cx,cy,timer]
coordinates.append(cycle)
f = h5py.File(fileName, 'a')
if moment["m00"] > 1000 / self.scale_down:
rect = cv2.minAreaRect(largest_contour)
rect = ((rect[0][0] * self.scale_down, rect[0][1] * self.scale_down), (rect[1][0] * self.scale_down, rect[1][1] * self.scale_down), rect[2])
box = cv2.cv.BoxPoints(rect)
box = np.int0(box)
cv2.drawContours(orig_img,[box], 0, (0, 0, 255), 2)
cv2.imshow("ColourTrackerWindow", orig_img)
#out.write(orig_img)
if cv2.waitKey(20) == 27:
cv2.destroyAllWindows()
...
self.capture.release()
#out.release()
f.close() # be CERTAIN to close the file
#testing_matrix.close()
break
if __name__ == "__main__":
colour_tracker = ColourTracker()
colour_tracker.run()
为了长度起见,我剪掉了一些部分,这就是“...”的用途。
您应该在该循环之后添加安全检查,以确保它找到了一些东西。
现在看来,即使什么也没找到,代码仍在执行:
import sys
import cv2
i = 0
found = False
for i in range(4):
capture = cv2.VideoCapture(i)
if not capture:
print "UNABLE TO CAPTURE CAMERA"
else:
found = True
print "taken camera from index: ", i
break
if found == False:
print "!!! No camera was found."
sys.exit()
在 Windows 上指定 DirectShow
capture = cv2.VideoCapture(i, cv2.CAP_DSHOW)