-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinfer-simple.py
More file actions
81 lines (69 loc) · 2.17 KB
/
infer-simple.py
File metadata and controls
81 lines (69 loc) · 2.17 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# load config
import cv2
import base64
import numpy as np
import requests
import time
from dotenv import load_dotenv
import os
# Load key-value pairs from .env file
load_dotenv()
# Construct the Roboflow Infer URL
# (if running locally replace https://detect.roboflow.com/ with eg http://127.0.0.1:9001/)
ROBOFLOW_MODEL = os.getenv("ROBOFLOW_MODEL")
ROBOFLOW_VERSION = os.getenv("ROBOFLOW_VERSION")
ROBOFLOW_API_KEY = os.getenv("ROBOFLOW_API_KEY")
ROBOFLOW_SIZE = 416
FRAMERATE = 24
BUFFER = 0.5
upload_url = "".join([
"https://detect.roboflow.com/",
ROBOFLOW_MODEL,
"/",
ROBOFLOW_VERSION,
"?api_key=",
ROBOFLOW_API_KEY,
"&format=image",
"&stroke=8",
"&confidence=30"
])
# Get webcam interface via opencv-python
video = cv2.VideoCapture(0)
# Infer via the Roboflow Infer API and return the result
def infer():
# Get the current image from the webcam
ret, img = video.read()
cv2.imshow('img', img)
# Resize (while maintaining the aspect ratio) to improve speed and save bandwidth
height, width, channels = img.shape
scale = ROBOFLOW_SIZE / max(height, width)
img = cv2.resize(img, (round(scale * width), round(scale * height)))
# Encode image to base64 string
retval, buffer = cv2.imencode('.jpg', img)
img_str = base64.b64encode(buffer)
# Get prediction from Roboflow Infer API
resp = requests.post(upload_url, data=img_str, headers={
"Content-Type": "application/x-www-form-urlencoded"
}, stream=True).raw
# Parse result image
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
# Main loop; infers sequentially until you press "q"
while 1:
# On "q" keypress, exit
if(cv2.waitKey(1) == ord('q')):
break
# Capture start time to calculate fps
start = time.time()
# Synchronously get a prediction from the Roboflow Infer API
image = infer()
# And display the inference results
if(image is None):
continue
cv2.imshow('image', image)
# Print frames per second
print((1/(time.time()-start)), " fps")
# Release resources when finished
video.release()
cv2.destroyAllWindows()