File size: 2,025 Bytes
9bd5ac0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()