Skip to content
Snippets Groups Projects
Commit c6ac6171 authored by Aymeric Chaumont's avatar Aymeric Chaumont
Browse files

cleanify cameras inventory, allow for multiple cams per restaurant, cleanify...

cleanify cameras inventory, allow for multiple cams per restaurant, cleanify rtsp capture, fix websockets in video-capture
parent bdaa59de
Branches
No related tags found
1 merge request!49improve cameras
Pipeline #44396 failed
...@@ -4,3 +4,4 @@ build/ ...@@ -4,3 +4,4 @@ build/
env/ env/
.env .env
__pycache__ __pycache__
cameras.py
\ No newline at end of file
restaurants = [
{
"restaurant": "local",
"a_factor": 30,
"b_factor": 120,
"cameras":
[
{
"IP": "",
"user": "",
"password": "",
"stream": "stream1",
"mask_points":
[
[
[70, 370],
[420, 720],
[1280, 720],
[1280, 250],
[930, 215],
[450, 550],
[130, 350]
]
]
}
]
}
]
...@@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware ...@@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv from dotenv import load_dotenv
from threading import Thread from threading import Thread
import os import os
from asyncio import run
from db import database, models from db import database, models
from routers import * from routers import *
...@@ -30,7 +31,7 @@ app.add_middleware( ...@@ -30,7 +31,7 @@ app.add_middleware(
async def on_startup(): async def on_startup():
# Database creation # Database creation
models.Base.metadata.create_all(bind=database.engine) models.Base.metadata.create_all(bind=database.engine)
t = Thread(target=handle_cameras) t = Thread(target=run, args=(handle_cameras(),))
t.start() t.start()
......
...@@ -3,50 +3,48 @@ from datetime import datetime, timedelta ...@@ -3,50 +3,48 @@ from datetime import datetime, timedelta
import numpy as np import numpy as np
import keras import keras
from utils.preprocessing import fix_singular_shape, norm_by_imagenet from utils.preprocessing import fix_singular_shape, norm_by_imagenet
from dotenv import load_dotenv
import json import json
import os import time
from cameras import restaurants
from db import models from db import models
from db.database import SessionLocal from db.database import SessionLocal
from routers.websocket import manager from routers.websocket import manager
def handle_cameras(): async def handle_cameras():
model = keras.models.load_model('assets', compile=False) model = keras.models.load_model('assets', compile=False)
db = SessionLocal() db = SessionLocal()
load_dotenv() for restaurant in restaurants:
camera_number = int(os.getenv('CAM_NUMBER')) for camera in restaurant["cameras"]:
cameras = []
for i in range(camera_number):
camera = {}
camera["place"] = os.getenv(f'CAM_{i}_PLACE')
camera["IP"] = os.getenv(f'CAM_{i}_IP')
camera["user"] = os.getenv(f'CAM_{i}_USER')
camera["password"] = os.getenv(f'CAM_{i}_PASSWORD')
camera["stream"] = os.getenv(f'CAM_{i}_STREAM')
camera["a_factor"] = int(os.getenv(f'CAM_{i}_A_FACTOR'))
camera["b_factor"] = int(os.getenv(f'CAM_{i}_B_FACTOR'))
camera["framegap"] = int(os.getenv(f'CAM_{i}_FRAMEGAP'))
camera["count"] = 0
camera["cap"] = cv2.VideoCapture(
f'rtsp://{camera["user"]}:{camera["password"]}@{camera["IP"]}/{camera["stream"]}')
mask_length = int(os.getenv(f'CAM_{i}_POINTS_NB'))
mask_points = []
for j in range(mask_length):
point = os.getenv(f'CAM_{i}_POINT_{j}')
mask_points.append(list(map(int, point.split(','))))
mask = np.zeros((720, 1280, 3), dtype=np.float32) mask = np.zeros((720, 1280, 3), dtype=np.float32)
cv2.fillPoly(mask, [np.array(mask_points)], (255, 255, 255)) cv2.fillPoly(mask, np.array(camera["mask_points"]), (255, 255, 255))
camera["mask"] = mask camera["mask"] = mask
cameras.append(camera)
while True: while True:
for camera in cameras:
if camera['cap'].isOpened(): start_timestamp = time.time()
ret, frame = camera['cap'].read() current_date = datetime.fromtimestamp(start_timestamp)
if ret and camera['count'] % camera['framegap'] == 0: print(current_date)
current_time = datetime.now() weekday, current_time = current_date.weekday(), current_date.time()
for restaurant in restaurants:
is_open = db.query(
models.OpeningHours).filter(
models.OpeningHours.place == restaurant["restaurant"],
models.OpeningHours.day == weekday,
models.OpeningHours.open_time <= current_time,
models.OpeningHours.close_time >= current_time).first() is not None
if is_open:
count_prediction = 0
cams_working = True
for camera in restaurant["cameras"]:
cap = cv2.VideoCapture(f'rtsp://{camera["user"]}:{camera["password"]}@{camera["IP"]}/{camera["stream"]}')
if cap.isOpened():
_, frame = cap.read()
masked_img = cv2.bitwise_and( masked_img = cv2.bitwise_and(
frame.astype(np.float32), camera["mask"]) frame.astype(np.float32), camera["mask"])
treated_img = fix_singular_shape(masked_img, 16) treated_img = fix_singular_shape(masked_img, 16)
...@@ -57,21 +55,23 @@ def handle_cameras(): ...@@ -57,21 +55,23 @@ def handle_cameras():
[treated_img]))), [treated_img]))),
axis=0) axis=0)
pred_map = np.squeeze(model.predict(input_image)) pred_map = np.squeeze(model.predict(input_image))
count_prediction = np.sum(pred_map) count_prediction += np.sum(pred_map)
else:
cams_working = False
cap.release()
if cams_working:
waiting_time = timedelta( waiting_time = timedelta(
seconds=camera['b_factor'] + seconds=restaurant['b_factor'] +
int(count_prediction) * int(count_prediction *
camera['a_factor']) restaurant['a_factor']))
db_record = models.Records( db_record = models.Records(
place=camera['place'], place=restaurant['restaurant'],
date=current_time, date=current_date,
density=int(count_prediction), density=int(count_prediction),
waiting_time=waiting_time) waiting_time=waiting_time)
db.add(db_record) db.add(db_record)
db.commit() db.commit()
manager.broadcast(json.dumps({"type": "data"})) await manager.broadcast(json.dumps({"type": "data"}))
camera['count'] += 1 print("owarida")
else: time.sleep(60 - time.time() + start_timestamp)
camera["cap"] = cv2.VideoCapture(
f"rtsp://{camera['user']}:{camera['password']}@{camera['IP']}/{camera['stream']}")
print("tentative de reconnexion")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment