所以我创建了一个类来打开VideoCapture()
并使用opencv读取帧。
import cv2
import imutils
class Camera():
def __init__(self):
self.cap = cv2.VideoCapture(0) # Prepare the camera...
print("Camera warming up ...")
self.ret, self.frame = self.cap.read()
def get_frame(self):
self.frames = open("stream.jpg", 'wb+')
s, img = self.cap.read()
if s: # frame captures without errors...
cv2.imwrite("stream.jpg", img) # Save image...
return self.frames.read()
def main():
while True:
cam1 = Camera().get_frame()
frame = imutils.resize(cam1, width=640)
cv2.imshow("Frame", frame)
return ()
if __name__ == '__main__':
main()
这给了我错误:
(h, w) = image.shape[:2]
AttributeError: 'bytes' object has no attribute 'shape'
此外,当我删除get_frame
函数并直接创建这样的构造函数时:
cam1 = Camera()
frame = imutils.resize(cam1.frame, width=640)
以递归方式创建相机对象。有人可以帮我解决我在这里做错了什么。
答案 0 :(得分:1)
您的代码存在一些问题:
__init__(self)
功能中初始化相机。为什么?您已在get_frame(self)
。get_frame(self)
中,最后它返回self.frames.read()
。您应该返回self.cap.read()
捕获的图像。这导致AttributeError
。Camera().release_camera()
来关闭网络摄像头。以下是重组后的代码(我没有使用imutils
,我只使用了cv2.resize()
):
import cv2
class Camera():
def __init__(self):
self.cap = cv2.VideoCapture(0) # Prepare the camera...
print("Camera warming up ...")
def get_frame(self):
s, img = self.cap.read()
if s: # frame captures without errors...
pass
return img
def release_camera(self):
self.cap.release()
def main():
while True:
cam1 = Camera().get_frame()
frame = cv2.resize(cam1, (0, 0), fx = 0.75, fy = 0.75)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Camera().release_camera()
return ()
if __name__ == '__main__':
main()
cv2.destroyAllWindows()