Skip to content

Commit

Permalink
Update for communication disconnection
Browse files Browse the repository at this point in the history
  • Loading branch information
KentaYoshioka committed Aug 20, 2024
1 parent f14b1d0 commit 45149fa
Showing 1 changed file with 75 additions and 101 deletions.
176 changes: 75 additions & 101 deletions people-counter/camera/detect.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,3 @@
# This program is delived from YOLOv5 examples.(https://github.com/ultralytics/yolov5)
"""
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
Usage - sources:
$ python detect.py --weights yolov5s.pt --source 0 # webcam
img.jpg # image
vid.mp4 # video
screen # screenshot
path/ # directory
'path/*.jpg' # glob
'https://youtu.be/Zgi9g1ksQHc' # YouTube
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
Usage - formats:
$ python detect.py --weights yolov5s.pt # PyTorch
yolov5s.torchscript # TorchScript
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
yolov5s_openvino_model # OpenVINO
yolov5s.engine # TensorRT
yolov5s.mlmodel # CoreML (macOS-only)
yolov5s_saved_model # TensorFlow SavedModel
yolov5s.pb # TensorFlow GraphDef
yolov5s.tflite # TensorFlow Lite
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
yolov5s_paddle_model # PaddlePaddle
"""

import argparse
import os
import platform
Expand All @@ -43,42 +15,38 @@
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
base_time = math.floor(time.time())
count_list = [0] * 100

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, smart_inference_mode

# ブローカーに接続できたときの処理
# Called when connected to the broker
def on_connect(client, userdata, flag, rc):
print("Connected with result code " + str(rc))
LOGGER.info("Connected with result code " + str(rc))

# ブローカーが切断したときの処理
# Called when disconnected from the broker
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection.")

# publishが完了したときの処理
def on_publish(client, userdata, mid):
print("publish: {0}".format(mid))
LOGGER.info("Unexpected disconnection.")
client.connect()

class MqttClient:
def __init__(self, server, port, topic):
self.topic = topic
self.client = mqtt.Client() # クラスのインスタンス(実体)の作成
self.client.on_connect = on_connect # 接続時のコールバック関数を登録
self.client.on_disconnect = on_disconnect # 切断時のコールバックを登録
self.client.on_publish = on_publish # メッセージ送信時のコールバック

self.client.connect(server, port, 60) # 接続先は自分自身
self.client = mqtt.Client()
self.client.on_connect = on_connect
self.client.on_disconnect = on_disconnect
self.client.connect(server, port, 60)

def publish(self, send_string):
self.client.publish(self.topic, send_string)

@smart_inference_mode()
def run(
weights=ROOT / 'yolov5s.pt', # model path or triton URL
weights=ROOT / 'yolov5x.pt', # model path or triton URL
source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam)
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
imgsz=(640, 640), # inference size (height, width)
Expand All @@ -105,56 +73,67 @@ def run(
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
vid_stride=1, # video frame-rate stride
mqtt_topic='',
mqtt_server='',
mqtt_topic='', # MQTT topic
mqtt_server='', # MQTT server
mqtt_port=1883,
mqtt_interval=10
):
source = str(source)
save_img = not nosave and not source.endswith('.txt') # save inference images
save_img = not nosave and not source.endswith('.txt')
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
screenshot = source.lower().startswith('screen')
if is_url and is_file:
source = check_file(source) # download
source = check_file(source)

# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Create directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)

# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
stride, names, pt = model.stride, model.names, model.pt
imgsz = check_img_size(imgsz, s=stride) # check image size

# Dataloader
bs = 1 # batch_size
if webcam:
view_img = check_imshow(warn=True)
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
bs = len(dataset)
elif screenshot:
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
else:
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
imgsz = check_img_size(imgsz, s=stride)

# Setup dataloader
bs = 1
try:
if webcam:
view_img = check_imshow(warn=True)
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
bs = len(dataset)
elif screenshot:
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
else:
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)

if dataset is None:
raise ValueError("Failed to load dataset")
except Exception as e:
LOGGER.error(f"Error loading stream: {e}")
if mqtt_server and mqtt_topic:
mqtt_client = MqttClient(mqtt_server, mqtt_port, mqtt_topic)
mqtt_client.publish("-1") # Send -1 when an error occurs
sys.exit(1)

vid_path, vid_writer = [None] * bs, [None] * bs

# Initialize MQTT client
if mqtt_server != '' and mqtt_topic != '':
if mqtt_server and mqtt_topic:
mqtt_client = MqttClient(mqtt_server, mqtt_port, mqtt_topic)

# Run inference
model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))
seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
for path, im, im0s, vid_cap, s in dataset:
with dt[0]:
im = torch.from_numpy(im).to(model.device)
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
im /= 255 # 0 - 255 to 0.0 - 1.0
im = im.half() if model.fp16 else im.float()
im /= 255
if len(im.shape) == 3:
im = im[None] # expand for batch dim
im = im[None]

# Inference
with dt[1]:
Expand All @@ -165,62 +144,56 @@ def run(
with dt[2]:
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)

# Second-stage classifier (optional)
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

# Process predictions
for i, det in enumerate(pred): # per image
for i, det in enumerate(pred):
seen += 1
if webcam: # batch_size >= 1
if webcam:
p, im0, frame = path[i], im0s[i].copy(), dataset.count
s += f'{i}: '
else:
p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

p = Path(p) # to Path
save_path = str(save_dir / p.name) # im.jpg
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt
s += '%gx%g ' % im.shape[2:] # print string
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
imc = im0.copy() if save_crop else im0 # for save_crop
p = Path(p)
save_path = str(save_dir / p.name)
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')
s += '%gx%g ' % im.shape[2:]

gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
imc = im0.copy() if save_crop else im0
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

# Print results
for content_num, c in enumerate(det[:, 5].unique()):
n = (det[:, 5] == c).sum() # detections per class
n = (det[:, 5] == c).sum()
global count_list
if content_num == 0:
if c == 0: # check if object is person
if c == 0:
count_list[n] += 1
else:
count_list[0] += 1

s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "

if (math.floor(time.time()) - base_time) % mqtt_interval == mqtt_interval - 1 and mqtt_server != '' and mqtt_topic != '':
if (math.floor(time.time()) - base_time) % mqtt_interval == mqtt_interval - 1 and mqtt_server and mqtt_topic:
mqtt_client.publish(f"{count_list.index(max(count_list))}")
count_list = [0] * 100
time.sleep(1)

# Write results
for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
if save_txt:
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
line = (cls, *xywh, conf) if save_conf else (cls, *xywh)
with open(f'{txt_path}.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')

if save_img or save_crop or view_img: # Add bbox to image
c = int(cls) # integer class
if save_img or save_crop or view_img:
c = int(cls)
label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
annotator.box_label(xyxy, label, color=colors(c, True))
if save_crop:
save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

# Stream results
im0 = annotator.result()
if view_img:
if platform.system() == 'Linux' and p not in windows:
Expand Down Expand Up @@ -249,17 +222,18 @@ def run(
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer[i].write(im0)

# Print time (inference-only)
LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")

# Print results
# Print inference timing per image
t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)

# Save results
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")

# If the model was updated, strip the optimizer
if update:
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
strip_optimizer(weights[0])


def parse_opt():
Expand All @@ -277,7 +251,7 @@ def parse_opt():
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--visualize', action='store_true', help='visualize features')
Expand All @@ -291,10 +265,10 @@ def parse_opt():
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
parser.add_argument('--mqtt-topic', type=str, default='', help='topic name at mqtt sending')
parser.add_argument('--mqtt-server', type=str, default='', help='mqtt server domain')
parser.add_argument('--mqtt-port', type=int, default=1883, help='mqtt server port')
parser.add_argument('--mqtt-interval', type=int, default=10, help='interval for mqtt publishing')
parser.add_argument('--mqtt-topic', type=str, default='', help='topic name for MQTT sending')
parser.add_argument('--mqtt-server', type=str, default='', help='MQTT server domain')
parser.add_argument('--mqtt-port', type=int, default=1883, help='MQTT server port')
parser.add_argument('--mqtt-interval', type=int, default=10, help='interval for MQTT publishing')
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(vars(opt))
Expand Down

0 comments on commit 45149fa

Please sign in to comment.