Skip to content

Instantly share code, notes, and snippets.

@kevinkit
Last active Oct 2, 2020
Embed
What would you like to do?
Easy OpenCV Camera class with clean up function
#!/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