people-counting / main.py
Alimustoofaa's picture
first commit
3e13f7c
raw
history blame
No virus
2.03 kB
import os
import cv2
import numpy as np
import gradio as gr
from PIL import Image
# Define path the model
PATH_PROTOTXT = os.path.join('saved_model/MobileNetSSD_deploy.prototxt')
PATH_MODEL = os.path.join('saved_model/MobileNetSSD_deploy.caffemodel')
# Define clasess model
CLASSES = [
'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle',
'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'hourse',
'motorbike', 'person', 'porredplant', 'sheep', 'sofa', 'train', 'tvmonitor'
]
# Load model
NET = cv2.dnn.readNetFromCaffe(PATH_PROTOTXT, PATH_MODEL)
def person_counting(image, threshold=0.7):
'''
Counting the number of people in the image
Args:
image: image to be processed
threshold: threshold to filter out the objects
Returns:
image: image with rectangles people detected
counting: count of people
'''
counting = 0
W, H = image.shape[1], image.shape[0]
blob = cv2.dnn.blobFromImage(image, 0.007843, (W, H), 127.5)
NET.setInput(blob); detections = NET.forward()
for i in np.arange(0, detections.shape[2]):
conf = detections[0, 0, i, 2]
idx = int(detections[0, 0, i, 1])
if CLASSES[idx] == 'person' and conf > threshold:
box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
x_min, y_min, x_max, y_max = box.astype('int')
counting += 1
cv2.rectangle(image, pt1=(x_min,y_min), pt2=(x_max,y_max), color=(255,0,0), thickness=1)
return image, counting
title = 'People counting'
css = ".image-preview {height: auto !important;}"
inputs = [gr.inputs.Image(source='upload'), gr.Slider(0, 1, value=0.5, label='threshold')]
outputs = [gr.outputs.Image(label='image output'), gr.Number(label='counting')]
examples = [[f'images/{i}', 0.5] for i in os.listdir('images')]
iface = gr.Interface(
title = title,
fn = person_counting,
inputs = inputs,
outputs = outputs,
examples= examples,
css=css
)
iface.launch()