Created
August 23, 2023 16:28
-
-
Save noodlehaus/cafa0687769f05a0766967692325529b to your computer and use it in GitHub Desktop.
Check if object of interest is within the bounding box.
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
import cv2 | |
from flask import Flask, Response | |
from ultralytics import YOLO | |
app = Flask(__name__) | |
model2 = YOLO("models/yolov8n-face.pt") | |
cam = cv2.VideoCapture(0) | |
if not cam.isOpened(): | |
raise RuntimeError("Failed to access camera.") | |
@app.route("/") | |
def index(): | |
return """ | |
<html> | |
<head> | |
<style> | |
body { margin: 0; padding: 0 } | |
img { width: 100%; } | |
</style> | |
<body><img src="/stream"></body> | |
</html> | |
""" | |
@app.route("/stream") | |
def stream(): | |
return Response(frames(), mimetype="multipart/x-mixed-replace; boundary=frame") | |
def frames(): | |
# our bounding box target | |
bx1, by1, bx2, by2 = 600, 400, 800, 600 | |
while True: | |
okay, frame = cam.read() | |
if not okay: | |
break | |
frame = cv2.flip(frame, 1) | |
results = model2(frame, verbose=False) | |
for face in results[0].boxes: | |
x1, y1, x2, y2 = face.xyxy[0] | |
rect(frame, x1, y1, x2, y2) | |
cx, cy = center(x1, y1, x2, y2) | |
label = f"{cx}, {cy}" | |
text(frame, label, 30, 40) | |
circle(frame, cx, cy, 30, (0, 255, 255)) | |
if cx > bx1 and cx < bx2 and cy > by1 and cy < by2: | |
rect(frame, bx1, by1, bx2, by2, (0, 255, 0)) | |
else: | |
rect(frame, bx1, by1, bx2, by2, (64, 64, 64)) | |
_, jpeg = cv2.imencode(".jpeg", frame) | |
yield (b"--frame\r\nContent-Type: image/jpeg\r\n\r\n" + jpeg.tobytes() + b"\r\n\r\n") | |
def text(image, text, x, y, color = (255, 255, 255)): | |
cv2.putText(image, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 3, cv2.LINE_AA) | |
def circle(image, x, y, r, color = (255, 255, 255)): | |
cv2.circle(image, (x, y), r, color, 2) | |
def rect(image, x1, y1, x2, y2, color = (255, 255, 255)): | |
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), color, 2) | |
def center(x1, y1, x2, y2): | |
return int(x1 + (x2 - x1)/2), int(y1 + (y2 - y1)/2) | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=8888, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment