how to implement yolo in python

You can implement YOLO (You Only Look Once) in Python for object detection using the following steps:

  1. Install the required packages:
main.py
pip install numpy
pip install opencv-python
44 chars
3 lines
  1. Download the YOLOv3 weights and configuration files from the official website or GitHub repository.

  2. Load the weights and configuration files:

main.py
import cv2
import numpy as np

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
360 chars
11 lines
  1. Load the input image:
main.py
img = cv2.imread("image_path.jpg")
height, width, channels = img.shape
71 chars
3 lines
  1. Prepare the input image for YOLO by performing blob conversion:
main.py
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), swapRB=True, crop=False)
80 chars
2 lines
  1. Run the forward propagation of the image through the network:
main.py
net.setInput(blob)
outs = net.forward(output_layers)
53 chars
3 lines
  1. Extract the bounding boxes, confidence scores, and class IDs for each object detected in the image:
main.py
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:
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)
            x = center_x - w // 2
            y = center_y - h // 2
            boxes.append([x, y, w, h])
            confidences.append(float(confidence))
            class_ids.append(class_id)
601 chars
19 lines
  1. Apply non-maximum suppression to remove the redundant detections:
main.py
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
57 chars
2 lines
  1. Draw the bounding boxes and their corresponding labels on the input image:
main.py
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        color = colors[class_ids[i]]
        cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
        cv2.putText(img, label, (x, y + 30), font, 1, color, 2)
316 chars
9 lines
  1. Show the final output image with the detected objects:
main.py
cv2.imshow("Output Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
71 chars
4 lines

And that's it! You have successfully implemented YOLO object detection in Python.

gistlibby LogSnag