import cv2
import numpy as np
import smbus
bus=smbus.SMBus(1)
address = 0x08

def writeNumber(value):
    bus.write_byte(address, value)
    return -1

cap = cv2.VideoCapture(0)
car_cascade = cv2.CascadeClassifier('cars.xml')
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
#print("Ancho: " + str(width))
#print("Alto: " + str(height))
area = (width * height) / 3
#print("Size: " + str(area))

while True:
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cars = car_cascade.detectMultiScale(gray, 1.1, 3)
    for (x,y,w,h) in cars:
        pos_x = max(x - 10, 0)
        pos_y = max(y - 10, 0)
    
        height2 = (y+h)-y
        width2 = (x+w)-x
        #print("Alto2: " + str(height2))
        #print("Ancho2: " + str(width2))
        area2 = height2 * width2
        #print("Area2: " + str(area2))
        porcentaje = (area2 * 100) / area
        #print (porcentaje)
        if(porcentaje > 10):
            if(x < (width/3)):
                if(cajon == 1):
                    cajon = 0
                else:
                    cajon = 1
            else:
                if(cajon == 2):
                    cajon = 0
                else:
                    cajon = 2
            cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
        else:
            cajon = 0

        #cv2.putText(frame, "Carrito en cajon " + str(cajon)+ str(" : %2.2f" % porcentaje) + "%", (pos_x,pos_y), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255,255,0),4,cv2.LINE_AA)
        writeNumber(cajon)
        print ("Carrito en cajon: " + str(cajon))

    #cv2.imshow('video', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()

