You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
python-backend/index.py

59 lines
2.0 KiB

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
5 years ago
from PIL import Image
5 years ago
import time
import os
import urllib.request
5 years ago
import camera
import image_tools
5 years ago
import config
config.bootstrap()
# Use a service account
5 years ago
cred = credentials.Certificate(os.getenv('FIREBASE_CERT_FILE'))
firebase_admin.initialize_app(cred)
db = firestore.client()
5 years ago
doc_conf = db.collection('configurations').document(os.getenv('CONFIG_CODE')).get().to_dict()
print(doc_conf)
5 years ago
def poll():
5 years ago
doc_ref_lot = db.collection('lots').document(doc_conf['lot_id'])
5 years ago
5 years ago
# Get the reference image
lot_info = doc_ref_lot.collection('info').document('lotInfo').get().to_dict()
urllib.request.urlretrieve(os.getenv('BACKEND_URL')+'img/references/'+lot_info['refImage'], './ref-img.jpg')
5 years ago
reference = Image.open('./ref-img.jpg').load()
5 years ago
# Take the picture
5 years ago
img = Image.open(camera.capture(doc_conf['stream'])).load()
5 years ago
#img = Image.open('./lib/test-images-vert/lot-3-cars.jpg').load()
5 years ago
5 years ago
doc_ref_stalls = doc_ref_lot.collection('stalls').get()
5 years ago
for stall in doc_ref_stalls:
5 years ago
stall_obj = stall.to_dict()
5 years ago
color_reference = image_tools.average_color(stall_obj['locationX'], stall_obj['locationY'], stall_obj['width'], stall_obj['height'], reference)
color_compare = image_tools.average_color(stall_obj['locationX'], stall_obj['locationY'], stall_obj['width'], stall_obj['height'], img)
5 years ago
stall_occupied = image_tools.threshold(image_tools.differences(color_reference, color_compare), float(doc_conf['e_hat']))
5 years ago
stall_obj['open'] = not stall_occupied
5 years ago
print("Updated: "+stall.id)
doc_ref_lot.collection('stalls').document(stall.id).set(stall_obj)
5 years ago
5 years ago
start_time = time.time()
5 years ago
5 years ago
while True:
poll()
5 years ago
doc_conf = db.collection('configurations').document(os.getenv('CONFIG_CODE')).get().to_dict()
print(doc_conf)
5 years ago
if doc_conf['stop']:
break
5 years ago
poll_time = float(doc_conf['frequency'])
5 years ago
time.sleep(poll_time - ((time.time() - start_time) % poll_time))