gpt4 book ai didi

python - 使用带有opencv python的网络摄像头显示带有waitkey()的黑屏

转载 作者:行者123 更新时间:2023-12-02 16:39:47 25 4
gpt4 key购买 nike

我正在尝试通过 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()

关于python - 使用带有opencv python的网络摄像头显示带有waitkey()的黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com