首页 > 解决方案 > 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.

标签: pythonopencv

解决方案


There are a few issues with your code:

  1. There is no need to initialize the camera in the __init__(self) function. Why? You are already calling it in get_frame(self).
  2. In function get_frame(self), at the end it returns self.frames.read() at the end. You are supposed to return the image captured by self.cap.read(). This resulted in AttributeError.
  3. 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()

推荐阅读