102 lines
2.5 KiB
Python

import json
import requests
import cv2
import numpy as np
from ultralytics import YOLO
from datetime import datetime, timedelta
import time
import pytz
import threading
# 2 car
# 3 motorbike
# 5 bus
# 7 truck
lock = threading.Lock()
def worker():
global run
global vd
send_url = 'http://localhost:3000/api/rawCameraData'
count_url = 'https://school.petrovv.com/api/counter'
i = 0
errors = 0
while True:
if errors > 5:
break
with lock:
if run != True:
break
try:
#start = time.monotonic_ns() / 1000000
response = requests.get(count_url)
cameraData = response.json()
cameraData = cameraData['camera']
response = requests.get(cameraData['img'])
response.raise_for_status()
arr = np.asarray(bytearray(response.content), dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
#imgDownload = time.monotonic_ns() / 1000000
results = vd(img, verbose=False)
#imgSee = time.monotonic_ns() / 1000000
count = 0
for r in results:
boxes = r.boxes
for box in boxes:
classNum = int(box.cls)
if classNum == 2 or classNum == 3 or classNum == 5 or classNum == 7:
count += 1
#imgCount = time.monotonic_ns() / 1000000
#print("download: {:7}, see: {:7}, count:{:7}".format(imgDownload - start, imgSee - imgDownload, imgCount - imgSee))
now_utc = datetime.now(pytz.utc) + timedelta(hours=2)
data = {'location_id': cameraData['location_id'], 'camera_id': cameraData['camera_id'], 'car_count': count, 'date': now_utc, 'hour': now_utc.hour}
response = requests.post(send_url, data=data)
# print(data)
if errors > 0:
errors = errors - 1
except:
print( 'Exception ' + str(i))
errors = errors + 1
i += 1
i = i % 1000
if i == 1:
print(datetime.now(pytz.utc) + timedelta(hours=2))
run = True
#vd = YOLO("Yolo-Weights/yolov8x.pt")
#vd = YOLO("Yolo-Weights/yolov8l.pt")
#vd = YOLO("Yolo-Weights/yolov8m.pt")
#vd = YOLO("Yolo-Weights/yolov8s.pt")
vd = YOLO("Yolo-Weights/yolov8n.pt")
t = threading.Thread(target=worker)
t.start()
name = input("Stop:")
with lock:
run = False
t.join()