Compare commits

..

4 Commits

Author SHA1 Message Date
blakeblackshear
a7d68a4998 increase queue size and add ability to take every nth frame 2019-04-19 08:23:07 -05:00
blakeblackshear
03e46efcdd add back queue full message 2019-04-19 06:37:29 -05:00
blakeblackshear
27e39edd65 add location masking for detected objects 2019-04-14 11:58:33 -05:00
blakeblackshear
4f829e818e implement person filtering with min/max by y position 2019-04-14 11:28:50 -05:00
7 changed files with 196 additions and 148 deletions

View File

@@ -1,59 +1,70 @@
FROM ubuntu:18.04
FROM ubuntu:16.04
# Install packages for apt repo
RUN apt-get -qq update && apt-get -qq install --no-install-recommends -y \
apt-transport-https \
ca-certificates \
curl \
wget \
gnupg-agent \
dirmngr \
software-properties-common
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys D986B59D
RUN echo "deb http://deb.odroid.in/5422-s bionic main" > /etc/apt/sources.list.d/odroid.list
RUN apt-get -qq update && apt-get -qq install --no-install-recommends -y \
python3 \
# OpenCV dependencies
ffmpeg \
# Install system packages
RUN apt-get -qq update && apt-get -qq install --no-install-recommends -y python3 \
python3-dev \
python-pil \
python-lxml \
python-tk \
build-essential \
cmake \
unzip \
pkg-config \
cmake \
git \
libgtk2.0-dev \
pkg-config \
libavcodec-dev \
libavformat-dev \
libswscale-dev \
libtbb2 \
libtbb-dev \
libjpeg-dev \
libpng-dev \
libtiff-dev \
libavcodec-dev \
libavformat-dev \
libswscale-dev \
libv4l-dev \
libxvidcore-dev \
libx264-dev \
libgtk-3-dev \
libatlas-base-dev \
gfortran \
python3-dev \
# Coral USB Python API Dependencies
libusb-1.0-0 \
python3-pip \
python3-pil \
libjasper-dev \
libdc1394-22-dev \
x11-apps \
wget \
vim \
ffmpeg \
unzip \
libusb-1.0-0-dev \
python3-setuptools \
python3-numpy \
libc++1 \
libc++abi1 \
libunwind8 \
libgcc1 \
zlib1g-dev \
libgoogle-glog-dev \
swig \
libunwind-dev \
libc++-dev \
libc++abi-dev \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install core packages
RUN wget -q -O /tmp/get-pip.py --no-check-certificate https://bootstrap.pypa.io/get-pip.py && python3 /tmp/get-pip.py
RUN pip install -U pip \
numpy \
pillow \
matplotlib \
notebook \
Flask \
imutils \
paho-mqtt \
PyYAML
# Install tensorflow models object detection
RUN GIT_SSL_NO_VERIFY=true git clone -q https://github.com/tensorflow/models /usr/local/lib/python3.5/dist-packages/tensorflow/models
RUN wget -q -P /usr/local/src/ --no-check-certificate https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-python-3.5.1.tar.gz
# Download & build protobuf-python
RUN cd /usr/local/src/ \
&& tar xf protobuf-python-3.5.1.tar.gz \
&& rm protobuf-python-3.5.1.tar.gz \
&& cd /usr/local/src/protobuf-3.5.1/ \
&& ./configure \
&& make \
&& make install \
&& ldconfig \
&& rm -rf /usr/local/src/protobuf-3.5.1/
# Download & build OpenCV
RUN wget -q -P /usr/local/src/ --no-check-certificate https://github.com/opencv/opencv/archive/4.0.1.zip
RUN cd /usr/local/src/ \
@@ -65,31 +76,30 @@ RUN cd /usr/local/src/ \
&& cmake -D CMAKE_INSTALL_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local/ .. \
&& make -j4 \
&& make install \
&& ldconfig \
&& rm -rf /usr/local/src/opencv-4.0.1
# Download and install EdgeTPU libraries for Coral
RUN wget https://dl.google.com/coral/edgetpu_api/edgetpu_api_latest.tar.gz -O edgetpu_api.tar.gz --trust-server-names
# Download and install EdgeTPU libraries
RUN wget -q -O edgetpu_api.tar.gz --no-check-certificate http://storage.googleapis.com/cloud-iot-edge-pretrained-models/edgetpu_api.tar.gz
RUN tar xzf edgetpu_api.tar.gz \
&& cd edgetpu_api \
&& cp -p libedgetpu/libedgetpu_arm32.so /usr/lib/arm-linux-gnueabihf/libedgetpu.so.1.0 \
&& ldconfig \
&& python3 -m pip install --no-deps "$(ls edgetpu-*-py3-none-any.whl 2>/dev/null)"
RUN cd /usr/local/lib/python3.6/dist-packages/edgetpu/swig/ \
&& ln -s _edgetpu_cpp_wrapper.cpython-35m-arm-linux-gnueabihf.so _edgetpu_cpp_wrapper.cpython-36m-arm-linux-gnueabihf.so
# symlink the model and labels
RUN wget https://dl.google.com/coral/canned_models/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite -O mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite --trust-server-names
RUN wget https://dl.google.com/coral/canned_models/coco_labels.txt -O coco_labels.txt --trust-server-names
RUN ln -s mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite /frozen_inference_graph.pb
RUN ln -s /coco_labels.txt /label_map.pbtext
&& cd python-tflite-source \
&& cp -p libedgetpu/libedgetpu_x86_64.so /lib/x86_64-linux-gnu/libedgetpu.so \
&& cp edgetpu/swig/compiled_so/_edgetpu_cpp_wrapper_x86_64.so edgetpu/swig/_edgetpu_cpp_wrapper.so \
&& cp edgetpu/swig/compiled_so/edgetpu_cpp_wrapper.py edgetpu/swig/ \
&& python3 setup.py develop --user
# Minimize image size
RUN (apt-get autoremove -y; \
apt-get autoclean -y)
# symlink the model and labels
RUN ln -s /python-tflite-source/edgetpu/test_data/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite /frozen_inference_graph.pb
RUN ln -s /python-tflite-source/edgetpu/test_data/coco_labels.txt /label_map.pbtext
# Set TF object detection available
ENV PYTHONPATH "$PYTHONPATH:/usr/local/lib/python3.5/dist-packages/tensorflow/models/research:/usr/local/lib/python3.5/dist-packages/tensorflow/models/research/slim"
RUN cd /usr/local/lib/python3.5/dist-packages/tensorflow/models/research && protoc object_detection/protos/*.proto --python_out=.
WORKDIR /opt/frigate/
ADD frigate frigate/
COPY detect_objects.py .

View File

@@ -62,12 +62,12 @@ camera:
platform: generic
still_image_url: http://<ip>:5000/<camera_name>/best_person.jpg
binary_sensor:
sensor:
- name: Camera Person
platform: mqtt
state_topic: "frigate/<camera_name>/objects"
value_template: '{{ value_json.person }}'
device_class: motion
device_class: moving
availability_topic: "frigate/available"
```

View File

@@ -3,8 +3,6 @@ web_port: 5000
mqtt:
host: mqtt.server.com
topic_prefix: frigate
# user: username # Optional -- Uncomment for use
# password: password # Optional -- Uncomment for use
cameras:
back:
@@ -15,20 +13,30 @@ cameras:
# values that begin with a "$" will be replaced with environment variable
password: $RTSP_PASSWORD
path: /cam/realmonitor?channel=1&subtype=2
mask: back-mask.bmp
regions:
- size: 350
x_offset: 0
y_offset: 300
min_person_area: 5000
threshold: 0.5
- size: 400
x_offset: 350
y_offset: 250
min_person_area: 2000
threshold: 0.5
- size: 400
x_offset: 750
y_offset: 250
min_person_area: 2000
threshold: 0.5
mask: back-mask.bmp
known_sizes:
- y: 300
min: 700
max: 1800
- y: 400
min: 3000
max: 7200
- y: 500
min: 8500
max: 20400
- y: 600
min: 10000
max: 50000
- y: 700
min: 10000
max: 125000

View File

@@ -36,12 +36,12 @@ def main():
client.loop_start()
# Queue for prepped frames, max size set to (number of cameras * 5)
max_queue_size = len(CONFIG['cameras'].items())*5
max_queue_size = len(CONFIG['cameras'].items())*10
prepped_frame_queue = queue.Queue(max_queue_size)
cameras = {}
for name, config in CONFIG['cameras'].items():
cameras[name] = Camera(name, config, prepped_frame_queue, client, MQTT_TOPIC_PREFIX)
cameras[name] = Camera(name, config, prepped_frame_queue, client, MQTT_TOPIC_PREFIX, DEBUG)
prepped_queue_processor = PreppedQueueProcessor(
cameras,

View File

@@ -38,7 +38,7 @@ class PreppedQueueProcessor(threading.Thread):
frame = self.prepped_frame_queue.get()
# Actual detection.
objects = self.engine.DetectWithInputTensor(frame['frame'], threshold=frame['region_threshold'], top_k=3)
objects = self.engine.DetectWithInputTensor(frame['frame'], threshold=0.5, top_k=3)
# parse and pass detected objects back to the camera
parsed_objects = []
for obj in objects:
@@ -59,7 +59,7 @@ class PreppedQueueProcessor(threading.Thread):
class FramePrepper(threading.Thread):
def __init__(self, camera_name, shared_frame, frame_time, frame_ready,
frame_lock,
region_size, region_x_offset, region_y_offset, region_threshold,
region_size, region_x_offset, region_y_offset,
prepped_frame_queue):
threading.Thread.__init__(self)
@@ -71,7 +71,6 @@ class FramePrepper(threading.Thread):
self.region_size = region_size
self.region_x_offset = region_x_offset
self.region_y_offset = region_y_offset
self.region_threshold = region_threshold
self.prepped_frame_queue = prepped_frame_queue
def run(self):
@@ -104,7 +103,6 @@ class FramePrepper(threading.Thread):
'frame_time': frame_time,
'frame': frame_expanded.flatten().copy(),
'region_size': self.region_size,
'region_threshold': self.region_threshold,
'region_x_offset': self.region_x_offset,
'region_y_offset': self.region_y_offset
})

View File

@@ -2,6 +2,7 @@ import time
import datetime
import threading
import cv2
from object_detection.utils import visualization_utils as vis_util
class ObjectCleaner(threading.Thread):
def __init__(self, objects_parsed, detected_objects):
@@ -81,10 +82,15 @@ class BestPersonFrame(threading.Thread):
best_frame = recent_frames[self.best_person['frame_time']]
best_frame = cv2.cvtColor(best_frame, cv2.COLOR_BGR2RGB)
# draw the bounding box on the frame
color = (255,0,0)
cv2.rectangle(best_frame, (self.best_person['xmin'], self.best_person['ymin']),
(self.best_person['xmax'], self.best_person['ymax']),
color, 2)
vis_util.draw_bounding_box_on_image_array(best_frame,
self.best_person['ymin'],
self.best_person['xmin'],
self.best_person['ymax'],
self.best_person['xmax'],
color='red',
thickness=2,
display_str_list=["{}: {}%".format(self.best_person['name'],int(self.best_person['score']*100))],
use_normalized_coordinates=False)
# convert back to BGR
self.best_frame = cv2.cvtColor(best_frame, cv2.COLOR_RGB2BGR)

View File

@@ -6,24 +6,25 @@ import threading
import ctypes
import multiprocessing as mp
import numpy as np
from object_detection.utils import visualization_utils as vis_util
from . util import tonumpyarray
from . object_detection import FramePrepper
from . objects import ObjectCleaner, BestPersonFrame
from . mqtt import MqttObjectPublisher
# fetch the frames as fast a possible and store current frame in a shared memory array
def fetch_frames(shared_arr, shared_frame_time, frame_lock, frame_ready, frame_shape, rtsp_url):
def fetch_frames(shared_arr, shared_frame_time, frame_lock, frame_ready, frame_shape, rtsp_url, take_frame=1):
# convert shared memory array into numpy and shape into image array
arr = tonumpyarray(shared_arr).reshape(frame_shape)
# start the video capture
video = cv2.VideoCapture()
video.open(rtsp_url)
print("Opening the RTSP Url...")
# keep the buffer small so we minimize old data
video.set(cv2.CAP_PROP_BUFFERSIZE,1)
bad_frame_counter = 0
frame_num = 0
while True:
# check if the video stream is still open, and reopen if needed
if not video.isOpened():
@@ -36,6 +37,9 @@ def fetch_frames(shared_arr, shared_frame_time, frame_lock, frame_ready, frame_s
# snapshot the time the frame was grabbed
frame_time = datetime.datetime.now()
if ret:
frame_num += 1
if (frame_num % take_frame) != 0:
continue
# go ahead and decode the current frame
ret, frame = video.retrieve()
if ret:
@@ -109,33 +113,70 @@ def get_rtsp_url(rtsp_config):
rtsp_config['password'], rtsp_config['host'], rtsp_config['port'],
rtsp_config['path'])
class CameraWatchdog(threading.Thread):
def __init__(self, camera):
threading.Thread.__init__(self)
self.camera = camera
def compute_sizes(frame_shape, known_sizes, mask):
# create a 3 dimensional numpy array to store estimated sizes
estimated_sizes = np.zeros((frame_shape[0], frame_shape[1], 2), np.uint32)
def run(self):
sorted_positions = sorted(known_sizes, key=lambda s: s['y'])
while True:
# wait a bit before checking
time.sleep(60)
last_position = {'y': 0, 'min': 0, 'max': 0}
next_position = sorted_positions.pop(0)
# if the next position has the same y coordinate, skip
while next_position['y'] == last_position['y']:
next_position = sorted_positions.pop(0)
y_change = next_position['y']-last_position['y']
min_size_change = next_position['min']-last_position['min']
max_size_change = next_position['max']-last_position['max']
min_step_size = min_size_change/y_change
max_step_size = max_size_change/y_change
if (datetime.datetime.now().timestamp() - self.camera.shared_frame_time.value) > 2:
print("last frame is more than 2 seconds old, restarting camera capture...")
self.camera.start_or_restart_capture()
time.sleep(5)
min_current_size = 0
max_current_size = 0
for y_position in range(frame_shape[0]):
# fill the row with the estimated size
estimated_sizes[y_position,:] = [min_current_size, max_current_size]
# if you have reached the next size
if y_position == next_position['y']:
last_position = next_position
# if there are still positions left
if len(sorted_positions) > 0:
next_position = sorted_positions.pop(0)
# if the next position has the same y coordinate, skip
while next_position['y'] == last_position['y']:
next_position = sorted_positions.pop(0)
y_change = next_position['y']-last_position['y']
min_size_change = next_position['min']-last_position['min']
max_size_change = next_position['max']-last_position['max']
min_step_size = min_size_change/y_change
max_step_size = max_size_change/y_change
else:
min_step_size = 0
max_step_size = 0
min_current_size += min_step_size
max_current_size += max_step_size
# apply mask by filling 0s for all locations a person could not be standing
if mask is not None:
pass
return estimated_sizes
class Camera:
def __init__(self, name, config, prepped_frame_queue, mqtt_client, mqtt_prefix):
def __init__(self, name, config, prepped_frame_queue, mqtt_client, mqtt_prefix, debug=False):
self.name = name
self.config = config
self.detected_objects = []
self.recent_frames = {}
self.rtsp_url = get_rtsp_url(self.config['rtsp'])
self.take_frame = self.config.get('take_frame', 1)
self.regions = self.config['regions']
self.frame_shape = get_frame_shape(self.rtsp_url)
self.mqtt_client = mqtt_client
self.mqtt_topic_prefix = '{}/{}'.format(mqtt_prefix, self.name)
self.debug = debug
# compute the flattened array length from the shape of the frame
flat_array_length = self.frame_shape[0] * self.frame_shape[1] * self.frame_shape[2]
@@ -153,24 +194,22 @@ class Camera:
# shape current frame so it can be treated as a numpy image
self.shared_frame_np = tonumpyarray(self.shared_frame_array).reshape(self.frame_shape)
self.capture_process = None
# create the process to capture frames from the RTSP stream and store in a shared array
self.capture_process = mp.Process(target=fetch_frames, args=(self.shared_frame_array,
self.shared_frame_time, self.frame_lock, self.frame_ready, self.frame_shape,
self.rtsp_url, self.take_frame))
self.capture_process.daemon = True
# for each region, create a separate thread to resize the region and prep for detection
self.detection_prep_threads = []
for region in self.config['regions']:
# set a default threshold of 0.5 if not defined
if not 'threshold' in region:
region['threshold'] = 0.5
if not isinstance(region['threshold'], float):
print('Threshold is not a float. Setting to 0.5 default.')
region['threshold'] = 0.5
self.detection_prep_threads.append(FramePrepper(
self.name,
self.shared_frame_np,
self.shared_frame_time,
self.frame_ready,
self.frame_lock,
region['size'], region['x_offset'], region['y_offset'], region['threshold'],
region['size'], region['x_offset'], region['y_offset'],
prepped_frame_queue
))
@@ -191,9 +230,6 @@ class Camera:
mqtt_publisher = MqttObjectPublisher(self.mqtt_client, self.mqtt_topic_prefix, self.objects_parsed, self.detected_objects)
mqtt_publisher.start()
# create a watchdog thread for capture process
self.watchdog = CameraWatchdog(self)
# load in the mask for person detection
if 'mask' in self.config:
self.mask = cv2.imread("/config/{}".format(self.config['mask']), cv2.IMREAD_GRAYSCALE)
@@ -201,28 +237,18 @@ class Camera:
self.mask = np.zeros((self.frame_shape[0], self.frame_shape[1], 1), np.uint8)
self.mask[:] = 255
def start_or_restart_capture(self):
if not self.capture_process is None:
print("Terminating the existing capture process...")
self.capture_process.terminate()
del self.capture_process
self.capture_process = None
# create the process to capture frames from the RTSP stream and store in a shared array
print("Creating a new capture process...")
self.capture_process = mp.Process(target=fetch_frames, args=(self.shared_frame_array,
self.shared_frame_time, self.frame_lock, self.frame_ready, self.frame_shape, self.rtsp_url))
self.capture_process.daemon = True
print("Starting a new capture process...")
self.capture_process.start()
# pre-compute estimated person size for every pixel in the image
if 'known_sizes' in self.config:
self.calculated_person_sizes = compute_sizes((self.frame_shape[0], self.frame_shape[1]),
self.config['known_sizes'], None)
else:
self.calculated_person_sizes = None
def start(self):
self.start_or_restart_capture()
self.capture_process.start()
# start the object detection prep threads
for detection_prep_thread in self.detection_prep_threads:
detection_prep_thread.start()
self.watchdog.start()
def join(self):
self.capture_process.join()
@@ -235,32 +261,27 @@ class Camera:
return
for obj in objects:
if obj['name'] == 'person':
person_area = (obj['xmax']-obj['xmin'])*(obj['ymax']-obj['ymin'])
# find the matching region
region = None
for r in self.regions:
if (
obj['xmin'] >= r['x_offset'] and
obj['ymin'] >= r['y_offset'] and
obj['xmax'] <= r['x_offset']+r['size'] and
obj['ymax'] <= r['y_offset']+r['size']
):
region = r
break
# if the min person area is larger than the
# detected person, don't add it to detected objects
if region and region['min_person_area'] > person_area:
continue
if self.debug:
# print out the detected objects, scores and locations
print(self.name, obj['name'], obj['score'], obj['xmin'], obj['ymin'], obj['xmax'], obj['ymax'])
# compute the coordinates of the person and make sure
# the location isnt outide the bounds of the image (can happen from rounding)
y_location = min(int(obj['ymax']), len(self.mask)-1)
x_location = min(int((obj['xmax']-obj['xmin'])/2.0), len(self.mask[0])-1)
location = (int(obj['ymax']), int((obj['xmax']-obj['xmin'])/2))
# if the person is in a masked location, continue
if self.mask[y_location][x_location] == [0]:
# if the person is in a masked location, continue
if self.mask[location[0]][location[1]] == [0]:
continue
if self.calculated_person_sizes is not None and obj['name'] == 'person':
person_size_range = self.calculated_person_sizes[location[0]][location[1]]
# if the person isnt on the ground, continue
if(person_size_range[0] == 0 and person_size_range[1] == 0):
continue
person_size = (obj['xmax']-obj['xmin'])*(obj['ymax']-obj['ymin'])
# if the person is not within 20% of the estimated size for that location, continue
if person_size < person_size_range[0] or person_size > person_size_range[1]:
continue
self.detected_objects.append(obj)
@@ -282,10 +303,15 @@ class Camera:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# draw the bounding boxes on the screen
for obj in detected_objects:
color = (255,0,0)
cv2.rectangle(frame, (obj['xmin'], obj['ymin']),
(obj['xmax'], obj['ymax']),
color, 2)
vis_util.draw_bounding_box_on_image_array(frame,
obj['ymin'],
obj['xmin'],
obj['ymax'],
obj['xmax'],
color='red',
thickness=2,
display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
use_normalized_coordinates=False)
for region in self.regions:
color = (255,255,255)