Skip to content

Commit 672eff5

Browse files
Update SDK experiments
1 parent d91dc82 commit 672eff5

File tree

83 files changed

+4057
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

83 files changed

+4057
-0
lines changed

gen2-blur-faces/sdk/main.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import cv2
2+
import numpy as np
3+
4+
from depthai_sdk import OakCamera
5+
6+
NN_WIDTH, NN_HEIGHT = 300, 300
7+
8+
9+
def callback(packet, visualizer):
10+
frame = packet.frame
11+
12+
for det in packet.detections:
13+
# Expand the bounding box
14+
x1, y1, x2, y2 = det.top_left[0], det.top_left[1], det.bottom_right[0], det.bottom_right[1]
15+
x1 *= 0.8
16+
y1 *= 0.8
17+
x2 *= 1.2
18+
y2 *= 1.2
19+
20+
bbox = np.int0([x1, y1, x2, y2])
21+
22+
face = frame[bbox[1]:bbox[3], bbox[0]:bbox[2]]
23+
fh, fw, fc = face.shape
24+
frame_h, frame_w, frame_c = frame.shape
25+
26+
# Create blur mask around the face
27+
mask = np.zeros((frame_h, frame_w), np.uint8)
28+
polygon = cv2.ellipse2Poly((bbox[0] + int(fw / 2), bbox[1] + int(fh / 2)), (int(fw / 2), int(fh / 2)), 0, 0,
29+
360, delta=1)
30+
cv2.fillConvexPoly(mask, polygon, 255)
31+
32+
frame_copy = frame.copy()
33+
frame_copy = cv2.blur(frame_copy, (80, 80))
34+
face_extracted = cv2.bitwise_and(frame_copy, frame_copy, mask=mask)
35+
background_mask = cv2.bitwise_not(mask)
36+
background = cv2.bitwise_and(frame, frame, mask=background_mask)
37+
# Blur the face
38+
frame = cv2.add(background, face_extracted)
39+
40+
cv2.imshow('Face blurring', frame)
41+
42+
43+
with OakCamera() as oak:
44+
color = oak.create_camera('color', fps=30)
45+
det_nn = oak.create_nn('face-detection-retail-0004', color)
46+
det_nn.config_nn(aspect_ratio_resize_mode='letterbox')
47+
48+
oak.callback(det_nn, callback=callback)
49+
oak.start(blocking=True)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
opencv-python
2+
depthai
3+
depthai-sdk
4+
numpy
5+
blobconverter

gen2-class-saver-jpeg/sdk/main.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import csv
2+
import time
3+
from pathlib import Path
4+
5+
import cv2
6+
from depthai_sdk import OakCamera
7+
8+
labels = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
9+
'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
10+
11+
# Create data folder
12+
Path('data').mkdir(parents=True, exist_ok=True)
13+
14+
15+
def create_folders():
16+
Path(f'data/raw').mkdir(parents=True, exist_ok=True)
17+
for text in labels:
18+
Path(f'data/{text}').mkdir(parents=True, exist_ok=True)
19+
20+
21+
def callback(packet, visualizer):
22+
original_frame = packet.frame
23+
24+
timestamp = int(time.time() * 10000)
25+
raw_frame_path = f'data/raw/{timestamp}.jpg'
26+
cv2.imwrite(raw_frame_path, original_frame)
27+
28+
frame = visualizer.draw(original_frame.copy())
29+
30+
for detection in packet.detections:
31+
bbox = (*detection.top_left, *detection.bottom_right)
32+
33+
det_frame = original_frame[bbox[1]:bbox[3], bbox[0]:bbox[2]]
34+
35+
cropped_path = f'data/{detection.label}/{timestamp}_cropped.jpg'
36+
overlay_path = f'data/{detection.label}/{timestamp}_overlay.jpg'
37+
38+
cv2.imwrite(cropped_path, det_frame)
39+
cv2.imwrite(overlay_path, frame)
40+
41+
data = {
42+
'timestamp': timestamp,
43+
'label': detection.label,
44+
'left': bbox[0],
45+
'top': bbox[1],
46+
'right': bbox[2],
47+
'bottom': bbox[3],
48+
'raw_frame': raw_frame_path,
49+
'overlay_frame': overlay_path,
50+
'cropped_frame': cropped_path,
51+
}
52+
dataset.writerow(data)
53+
54+
cv2.imshow('Class saver', frame)
55+
56+
57+
with OakCamera() as oak, open('data/dataset.csv', 'w') as csvfile:
58+
create_folders()
59+
60+
dataset = csv.DictWriter(csvfile, ['timestamp', 'label', 'left', 'top', 'right', 'bottom',
61+
'raw_frame', 'overlay_frame', 'cropped_frame'])
62+
dataset.writeheader()
63+
64+
color = oak.create_camera('color')
65+
nn = oak.create_nn('mobilenet-ssd', color)
66+
67+
oak.visualize(nn.out.main, callback=callback, fps=True)
68+
oak.start(blocking=True)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
opencv-python
2+
depthai
3+
blobconverter
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from depthai_sdk import OakCamera
2+
3+
with OakCamera() as oak:
4+
color = oak.create_camera('color', resolution='4K', encode='h264')
5+
oak.record(color.out.main, path='records')
6+
7+
oak.start(blocking=True)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
av
2+
depthai
3+
depthai-sdk

gen2-crowdcounting/sdk/main.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import cv2
2+
import numpy as np
3+
4+
from depthai_sdk import OakCamera
5+
6+
NN_WIDTH = 426
7+
NN_HEIGHT = 240
8+
9+
10+
def callback(packet, visualizer):
11+
nn_data = packet.img_detections
12+
lay1 = np.array(nn_data.getFirstLayerFp16()).reshape((30, 52)) # density map output is 1/8 of input size
13+
count = np.sum(lay1) # predicted count is the sum of the density map
14+
cv2.putText(packet.frame, f'Predicted count: {count:.2f}', (2, 30),
15+
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2)
16+
17+
output = np.array(lay1) * 255
18+
output = output.astype(np.uint8)
19+
output_colors = cv2.applyColorMap(output, cv2.COLORMAP_VIRIDIS)
20+
output_colors = cv2.resize(output_colors, (packet.frame.shape[1], packet.frame.shape[0]),
21+
interpolation=cv2.INTER_LINEAR)
22+
23+
cv2.addWeighted(packet.frame, 1.0, output_colors, 0.5, 0, packet.frame)
24+
cv2.imshow('Crowd counting', packet.frame)
25+
26+
27+
with OakCamera(replay='../vids/vid1.mp4') as oak:
28+
color = oak.create_camera('color', fps=5)
29+
nn = oak.create_nn('../models/vgg_openvino_2021.4_6shave.blob', color)
30+
31+
oak.callback(nn.out.main, callback=callback)
32+
oak.start(blocking=True)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
opencv-python
2+
depthai
3+
depthai-sdk
4+
gdown
5+
numpy
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import cv2
2+
import numpy as np
3+
from depthai import TrackerType, TrackerIdAssignmentPolicy, Tracklet
4+
5+
from depthai_sdk import OakCamera, BboxStyle, TextPosition
6+
7+
tracked_objects = {}
8+
counter = {'up': 0, 'down': 0, 'left': 0, 'right': 0}
9+
10+
ROI_POS = 0.5
11+
AXIS = 1
12+
13+
14+
class TrackableObject:
15+
def __init__(self, objectID, centroid):
16+
# store the object ID, then initialize a list of centroids
17+
# using the current centroid
18+
self.objectID = objectID
19+
self.centroids = [centroid]
20+
21+
# initialize a boolean used to indicate if the object has
22+
# already been counted or not
23+
self.counted = False
24+
25+
26+
def get_centroid(roi):
27+
x1 = roi.topLeft().x
28+
y1 = roi.topLeft().y
29+
x2 = roi.bottomRight().x
30+
y2 = roi.bottomRight().y
31+
return ((x2 - x1) / 2 + x1, (y2 - y1) / 2 + y1)
32+
33+
34+
def callback(packet, visualizer):
35+
height, width = packet.frame.shape[:2]
36+
37+
for t in packet.daiTracklets.tracklets:
38+
to = tracked_objects.get(t.id, None)
39+
40+
# calculate centroid
41+
roi = t.roi.denormalize(width, height)
42+
x1 = int(roi.topLeft().x)
43+
y1 = int(roi.topLeft().y)
44+
x2 = int(roi.bottomRight().x)
45+
y2 = int(roi.bottomRight().y)
46+
centroid = (int((x2 - x1) / 2 + x1), int((y2 - y1) / 2 + y1))
47+
48+
# If new tracklet, save its centroid
49+
if t.status == Tracklet.TrackingStatus.NEW:
50+
to = TrackableObject(t.id, centroid)
51+
elif to is not None and not to.counted:
52+
if AXIS == 0:
53+
x = [c[0] for c in to.centroids]
54+
direction = centroid[0] - np.mean(x)
55+
56+
if centroid[0] > ROI_POS * width and direction > 0 and np.mean(x) < ROI_POS * width:
57+
counter['right'] += 1
58+
to.counted = True
59+
elif centroid[0] < ROI_POS * width and direction < 0 and np.mean(x) > ROI_POS * width:
60+
counter['left'] += 1
61+
to.counted = True
62+
63+
elif AXIS == 1:
64+
y = [c[1] for c in to.centroids]
65+
direction = centroid[1] - np.mean(y)
66+
67+
if centroid[1] > ROI_POS * height and direction > 0 and np.mean(y) < ROI_POS * height:
68+
counter['down'] += 1
69+
to.counted = True
70+
elif centroid[1] < ROI_POS * height and direction < 0 and np.mean(y) > ROI_POS * height:
71+
counter['up'] += 1
72+
to.counted = True
73+
74+
to.centroids.append(centroid)
75+
76+
tracked_objects[t.id] = to
77+
78+
if t.status != Tracklet.TrackingStatus.LOST and t.status != Tracklet.TrackingStatus.REMOVED:
79+
text = 'ID {}'.format(t.id)
80+
81+
cv2.putText(packet.frame, text, (centroid[0] - 10, centroid[1] - 10),
82+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
83+
cv2.circle(packet.frame, (centroid[0], centroid[1]), 4, (255, 255, 255), -1)
84+
85+
counter_str = f'Up: {counter["up"]}\nDown: {counter["down"]}\n' \
86+
if AXIS == 1 \
87+
else f'Left: {counter["left"]}\nRight: {counter["right"]}'
88+
89+
visualizer.add_line(pt1=(0, int(ROI_POS * height)),
90+
pt2=(width, int(ROI_POS * height)),
91+
color=(255, 255, 255),
92+
thickness=2)
93+
94+
visualizer.add_text(counter_str, position=TextPosition.BOTTOM_LEFT)
95+
frame = visualizer.draw(packet.frame)
96+
97+
cv2.imshow('People tracking', frame)
98+
99+
100+
with OakCamera(replay='../demo/example_01.mp4') as oak:
101+
color = oak.create_camera('color')
102+
nn = oak.create_nn('mobilenet-ssd', color, nn_type='mobilenet', tracker=True)
103+
104+
nn.config_tracker(tracker_type=TrackerType.ZERO_TERM_COLOR_HISTOGRAM,
105+
assignment_policy=TrackerIdAssignmentPolicy.SMALLEST_ID)
106+
107+
visualizer = oak.visualize(nn.out.tracker, callback=callback, fps=True)
108+
visualizer.detections(
109+
hide_label=True,
110+
bbox_style=BboxStyle.ROUNDED_RECTANGLE
111+
)
112+
113+
oak.start(blocking=True)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
numpy>=1.21
2+
opencv_python
3+
depthai
4+
depthai-sdk
5+
scipy
6+
blobconverter

0 commit comments

Comments
 (0)