# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 20:11:18 2020

@author: JAY KISHAN OMAR
"""

import cv2
import numpy as np
import matplotlib.pyplot as plt


net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []


with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
    
layers = net.getLayerNames()
output_layers = [layers[i[0]-1] for i in net.getUnconnectedOutLayers()]

print(classes)
print(output_layers)

colors = np.random.uniform(0, 255, size = (len(classes), 3))
image = cv2.imread(r"testing_image2.jpg")
image = cv2.resize(image, None, fx = 0.5, fy = 0.5)
height, width, channels = image.shape
print(height, width)

blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0,0,0), True, crop = False)

#for the representation of blob
#for b in blob:
#    for n,image_blob in enumerate(b):
#        cv2.imshow(str(n), image_blob)

        
net.setInput(blob)
outs = net.forward(output_layers)

boxes = []
confidences = []
class_ids = []



for out in outs:
    for detection in out:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence>0.5:
            center_x = int(detection[0]*width)
            center_y = int(detection[1]*height)
            w = int(detection[2]*width)
            h = int(detection[3]*height)
            x = int(center_x - w/2)
            y = int(center_y - h/2)
            boxes.append([x,y,w,h])
            confidences.append(float(confidence))
            class_ids.append(class_id)
           
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)            
for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        color = colors[i]
        cv2.circle(image, (center_x, center_y), 10, color, 2)
        cv2.rectangle(image, (x,y), (x+w, y+h), color, 2)
        cv2.putText(image, label, (x,y+2), cv2.FONT_HERSHEY_PLAIN, 2, color, 2)
plt.imshow(image)        
cv2.imshow("image", image) 
cv2.waitKey(0)
cv2.destroyAllWindows()