Last active
October 2, 2020 12:57
-
-
Save kevinkit/9b93ab3e28d3759579cb6fe864f36644 to your computer and use it in GitHub Desktop.
Easy OpenCV Camera class with clean up function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
Created on Fri Oct 2 14:43:23 2020 | |
@author: khoefle | |
""" | |
import cv2 | |
class OpenCVCamera(): | |
def __init__(self, | |
camid=None, | |
width=224, | |
height=224, | |
error_level=0): | |
self.camid = camid | |
self.width = width | |
self.height = height | |
# open camera | |
if camid is None: | |
self.cap = cv2.VideoCapture(0) | |
else: | |
self.cap = cv2.VideoCapture(camid) | |
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH,width) | |
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT,height) | |
self.error_level = error_level | |
def __enter__(self): | |
return self | |
def __exit__(self,exc_type, exc_value, traceback): | |
self.cap.release() | |
def getFrame(self): | |
""" | |
will return a frame | |
""" | |
ret,frame = self.cap.read() | |
if ret: | |
return frame | |
else: | |
if self.error_level == 1: | |
print("could not read image") | |
elif self.error_level > 1: | |
raise IOError("Could not read image") | |
if __name__ == "__main__": | |
with OpenCVCamera(error_level=2) as cam: | |
while True: | |
frame = cam.getFrame() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment