File size: 1,142 Bytes
c7cce82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import cv2
import requests
import json

API_URL = "http://127.0.0.1:7860/api/predict"

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cv2.namedWindow("API Truth View", cv2.WINDOW_NORMAL)

print("Press 'q' to quit")

while True:
    ret, frame = cap.read()
    if not ret:
        print("Camera read failed")
        break

    # encode frame as JPEG
    success, buffer = cv2.imencode(".jpg", frame)
    if not success:
        continue

    files = {
        "file": ("frame.jpg", buffer.tobytes(), "image/jpeg")
    }

    try:
        response = requests.post(API_URL, files=files, timeout=2)
        data = response.json()
    except Exception as e:
        data = {"error": str(e)}

    # pretty-print API output on frame
    text = json.dumps(data, indent=2)

    y = 30
    for line in text.split("\n"):
        cv2.putText(
            frame,
            line,
            (10, y),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.45,
            (0, 255, 0),
            1
        )
        y += 18

    cv2.imshow("API Truth View", frame)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()