-
Notifications
You must be signed in to change notification settings - Fork 0
/
picamera.py
175 lines (143 loc) · 5.57 KB
/
picamera.py
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import argparse
import sys
import time
import RPi.GPIO as GPIO
import cv2
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
from utils import visualize
from picamera2 import Picamera2
# Global variables to calculate FPS
COUNTER, FPS = 0, 0
START_TIME = time.time()
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640,480)
picam2.preview_configuration.main.format = "RGB888"
picam2.preview_configuration.align()
picam2.configure("preview")
picam2.start()
servo_pin = 22
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(servo_pin, GPIO.OUT)
if 'pwm' not in globals():
pwm = GPIO.PWM(servo_pin, 50)
pwm.start(0)
def run(model: str, max_results: int, score_threshold: float,
camera_id: int, width: int, height: int) -> None:
"""Continuously run inference on images acquired from the camera.
Args:
model: Name of the TFLite object detection model.
max_results: Max number of detection results.
score_threshold: The score threshold of detection results.
camera_id: The camera id to be passed to OpenCV.
width: The width of the frame captured from the camera.
height: The height of the frame captured from the camera.
"""
#cap = cv2.VideoCapture(0)
#cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
#cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
# Visualization parameters
row_size = 50 # pixels
left_margin = 24 # pixels
text_color = (0, 0, 0) # black
font_size = 1
font_thickness = 1
fps_avg_frame_count = 10
detection_frame = None
detection_result_list = []
def save_result(result: vision.ObjectDetectorResult, unused_output_image: mp.Image, timestamp_ms: int):
global FPS, COUNTER, START_TIME
# Calculate the FPS
if COUNTER % fps_avg_frame_count == 0:
FPS = fps_avg_frame_count / (time.time() - START_TIME)
START_TIME = time.time()
detection_result_list.append(result)
COUNTER += 1
# Initialize the object detection model
base_options = python.BaseOptions(model_asset_path=model)
options = vision.ObjectDetectorOptions(base_options=base_options,
running_mode=vision.RunningMode.LIVE_STREAM,
max_results=max_results, score_threshold=score_threshold,
result_callback=save_result)
detector = vision.ObjectDetector.create_from_options(options)
# Continuously capture images from the camera and run inference
while True:
im= picam2.capture_array()
#success, image = cap.read()
image=cv2.resize(im,(640,480))
image = cv2.flip(image, -1)
# Convert the image from BGR to RGB as required by the TFLite model.
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_image)
# Run object detection using the model.
detector.detect_async(mp_image, time.time_ns() // 1_000_000)
# Show the FPS
fps_text = 'FPS = {:.1f}'.format(FPS)
text_location = (left_margin, row_size)
current_frame = image
cv2.putText(current_frame, fps_text, text_location, cv2.FONT_HERSHEY_DUPLEX,
font_size, text_color, font_thickness, cv2.LINE_AA)
if detection_result_list:
# print(detection_result_list[0].detections[0].categories[0].category_name)
current_frame = visualize(current_frame, detection_result_list[0])
detection_frame = current_frame
if detection_result_list and detection_result_list[0].detections[0].categories[0].category_name == "helmet" :
print("Helmet detected. Turning on motor.")
pwm.start(7.5)
else:
print("No helmet detected. Turning off motor.")
pwm.start(0)
detection_result_list.clear()
if detection_frame is not None:
cv2.imshow('object_detection', detection_frame)
# Stop the program if the ESC key is pressed.
if cv2.waitKey(1) == 27:
break
detector.close()
cap.release()
cv2.destroyAllWindows()
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--model',
help='Path of the object detection model.',
required=False,
# default='efficientdet_lite0.tflite')
default='best.tflite')
parser.add_argument(
'--maxResults',
help='Max number of detection results.',
required=False,
default=1)
parser.add_argument(
'--scoreThreshold',
help='The score threshold of detection results.',
required=False,
type=float,
default=0.25)
# Finding the camera ID can be very reliant on platform-dependent methods.
# One common approach is to use the fact that camera IDs are usually indexed sequentially by the OS, starting from 0.
# Here, we use OpenCV and create a VideoCapture object for each potential ID with 'cap = cv2.VideoCapture(i)'.
# If 'cap' is None or not 'cap.isOpened()', it indicates the camera ID is not available.
parser.add_argument(
'--cameraId', help='Id of camera.', required=False, type=int, default=0)
parser.add_argument(
'--frameWidth',
help='Width of frame to capture from camera.',
required=False,
type=int,
default=640)
parser.add_argument(
'--frameHeight',
help='Height of frame to capture from camera.',
required=False,
type=int,
default=480)
args = parser.parse_args()
run(args.model, int(args.maxResults),
args.scoreThreshold, int(args.cameraId), args.frameWidth, args.frameHeight)
if __name__ == '__main__':
main()