import cv2
from darkflow.net.build import TFNet
import numpy as np
import time
import socket
import io
import struct

client_socket = socket.socket()
client_socket.connect(('192.168.1.76', 8000))
connection = client_socket.accept()[0].makefile(mode="rb")

options = {
'model': 'cfg/yolov2-tiny.cfg',
'load' : 'bin/yolov2-tiny.weights',
'threshold': 0.5
}
#capture = cv2.VideoCapture(0)
tfnet = TFNet(options)
colors = [tuple(255*np.random.rand(3)) for i in range(100)]

while (True):
    image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
    if not image_len:
        breakom
    image_stream = io.BytesIO()
    image_stream.write(connection.read(image_len))
    image_stream.seek(0)
    frame = cv2.imdecode(np.fromstring(image_stream.read(), np.uint8), 1)
    stime = time.time()
    results = tfnet.return_predict(frame)
    #no of objects detected
    objs_detected = len(results)
    if ret:
        for color,result in zip(colors,results):
            #bounding box topleft, bottomright coords, label & confidence
            tl = (result['topleft']['x'], result['topleft']['y'])
            br = (result['bottomright']['x'], result['bottomright']['y'])
            label = result['label']
            conf = result['confidence']
            #code to draw bounding box
            frame = cv2.rectangle(frame, tl, br, color, 3)
            frame = cv2.putText(frame, label,tl , cv2.FONT_HERSHEY_COMPLEX, 0.75, (225,255,0), 2)
            frame = cv2.putText(frame, str(int(conf*100))+'%', br, cv2.FONT_HERSHEY_DUPLEX, 0.75, (225,255,0), 2)
        cv2.imshow('frame',frame)
        print('fps {:.2f}'.format(1/(time.time()-stime)))
        print('objects detected:', objs_detected)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
cv2.destroyAllWindows()
