python - How to use OpenCV with Object Oriented
问题描述
So I created a class to open VideoCapture()
and read frames using 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()
This gives me error as:
(h, w) = image.shape[:2]
AttributeError: 'bytes' object has no attribute 'shape'
Also, when I remove the get_frame
function and directly created a constructor like this:
cam1 = Camera()
frame = imutils.resize(cam1.frame, width=640)
The camera object is created recursively created. Can someone help about what I am doing wrong here.
解决方案
There are a few issues with your code:
- There is no need to initialize the camera in the
__init__(self)
function. Why? You are already calling it inget_frame(self)
. - In function
get_frame(self)
, at the end it returnsself.frames.read()
at the end. You are supposed to return the image captured byself.cap.read()
. This resulted inAttributeError
. - I also added
Camera().release_camera()
to turn off the webcam once the execution is over.
Here is the restructured code (I did not use imutils
, I just used 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()
推荐阅读
- r - R-Markdown中数字向量的均匀间距
- c++ - 加载图像但没有存储在其数组中(C++,stbi_load)
- arrays - 为什么我不能使用 redux 从 Reactjs 中的数组中删除元素
- swift - 使用 SwiftUI 在 iPad 上纵向停靠侧边栏
- kubernetes - Kubernetes 运营商
- neo4j - Neo4j 使用列表匹配
- snowflake-cloud-data-platform - 将 MS SQL 转换为 Snowflake SQL,如何使用子查询返回记录计数
- javascript - 覆盖 Qt 安装程序框架 Next 按钮单击操作
- c# - C# - FatalExecutionEngineError 将再见数组编组为包含空终止双字节字符串的结构
- jquery - 使用 Travery css/html 和 jquery 创建的计数器编辑