# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import os
import numpy as np
import cv2
os.getcwd()

# cd D:\yolo\keras-yolo3

net = cv2.dnn.readNet('yolov3.weights','yolov3.cfg')
classes = []
with open(os.getcwd() + '\model_data\coco_classes.txt','r') as f:
    classes = [line.strip() for line in f.readlines()]
print("There are {} classes".format(len(classes)))

layer_names = net.getLayerNames()
outputLayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

img = cv2.imread(os.getcwd() + '\images\giraffe.jpg')
img = cv2.resize(img,(608,608))
height, width, channels = img.shape
print(img.shape)

cv2.imshow("Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

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

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

confidence_threshold = 0.5

class_ids = []
confidences = []
boxes = []
for out in outs:
    for detection in out:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > confidence_threshold:
            center_x = int(detection[0]*width)
            center_y = int(detection[1]*height)
            w = int(detection[2]*width)
            h = int(detection[3]*height)
            #cv2.circle(img,(center_x,center_y),10,(0,255,0),2)
            x = int(center_x - w/2)
            y = int(center_y - h/2)
            #cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
            boxes.append([x,y,w,h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

# +
indexes = cv2.dnn.NMSBoxes(boxes,confidences,score_threshold = confidence_threshold,nms_threshold = 0.6)
area = []
centers = []
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
    if i in indexes:
        x,y,w,h = boxes[i]
        area.append((w*h)/(width*height))
        label = str(classes[class_ids[i]])
        #color = colors[i]
        centers.append([x,y])
        cv2.rectangle(img,(x,y),(x+w,y+h),2)#color,2)
        cv2.putText(img,label,(x,y+30),font,1,(255,255,255),2)
        
cv2.imshow("Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# -

for index,value in enumerate(area):
    print("Area of object {} is {}".format(index,value))
    print("center of object : \n x = {}, y = {}".format(centers[index][0],centers[index][1]))



StarcoderdataJupyterScriptsDedupFiltered