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

# +
import cv2
import numpy as np
import time
net = cv2.dnn.readNet("C:/Users/tarun/Desktop/yolov3 object detection/yolov3_training_last (1).weights", "C:/Users/tarun/Desktop/yolov3 object detection/yolo_custom_detection/yolov3_testing.cfg")
classes = ["ball"]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
camera = cv2.VideoCapture(0)

while True:
    _,image = camera.read()
    height, width, channels = image.shape

    # Detecting objects
    blob = cv2.dnn.blobFromImage(image, 0.00392, (320, 320), (0, 0, 0), True, crop=False)
    net.setInput(blob)
    outs = net.forward(output_layers)
    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 > 0.5:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)
                # Rectangle coordinates
                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)

    font = cv2.FONT_HERSHEY_PLAIN
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            color = (0, 0, 255)
            cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
            cv2.putText(image, label, (x, y -10), font, 3, color, 3)
            tlc=(x,y)
            trc=(x+h,y)
            blc=(x,y+h)
            brc=(x+w,y+h)
            center=(center_x,center_y)
            height=h
            width=w
            print("Center of Box:",center,"Height and width:",(h,w),"Coordinates:",tlc,trc,blc,brc)        
    cv2.imshow("Image", image)
    key = cv2.waitKey(1)
    if key == 27:
        break
camera.release()
cv2.destroyAllWindows()
# -



StarcoderdataJupyterScriptsDedupFiltered