Skip to content

Instantly share code, notes, and snippets.

@korantu
Last active September 11, 2024 04:08
Show Gist options
  • Save korantu/aca93459573f6f4a03f306f562c6f15f to your computer and use it in GitHub Desktop.
Save korantu/aca93459573f6f4a03f306f562c6f15f to your computer and use it in GitHub Desktop.
camera infrastructure and kit
# main
import cv2
from threading import Thread
from json import load, dump
from pathlib import Path
CFG_FILE = Path('config.json')
class Config:
def __init__(self):
self.detect_faces = False
def save(self, path):
with open(path, 'w') as f:
dump(self.__dict__, f)
def load(self, path):
if not path.exists():
return
with open(path, 'r') as f:
data = load(f)
self.__dict__.update(data)
CFG = Config()
CFG.load(CFG_FILE)
# commands
import enum
class Command(enum.Enum):
QUIT = "q"
FACES = "f"
RESTART = "r"
ROI = "i"
command = []
def is_command(cmd: Command):
if cmd in command:
command.remove(cmd)
return True
return False
def reader():
options = ""
for cmd in Command:
options += f"{cmd.name}: {cmd.value} |"
while True:
read = input(options)
print(f"Command: {read}")
try:
asking = Command(read)
command.append(asking)
# some commands are final
if asking == Command.QUIT:
break
except ValueError:
print("Invalid command")
continue
Thread(target=reader, daemon=True).start()
def frame_generator():
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
yield frame
def main_opencv():
frame_count = 0
for frame in frame_generator():
frame_count += 1
# rotate right
frame = cv2.resize(frame, (480, 640))
# put frame number on the image
cv2.putText(frame, f"F: {frame_count}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if is_command(Command.QUIT):
break
if is_command(Command.FACES):
CFG.detect_faces = not CFG.detect_faces
print(f"Detect faces: {CFG.detect_faces}")
CFG.save(CFG_FILE)
if is_command(Command.RESTART):
return True
return False
def main():
while main_opencv():
...
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment