6. Advanced Deep Learning Architectures
AIM: Implement Object Detection Using YOLO.
PROGRAM:
import cv2
import numpy as np
# Load YOLO model
net = cv2.dnn.readNet("/content/drive/MyDrive/6-3/yolov3.weights", "/content/drive/MyDrive/6-3/yolov3.cfg")
classes = []
with open("/content/drive/MyDrive/6-3/classes.txt", "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()]
layer_names = net.getLayerNames()
# Get the names of the output layers (unconnected layers)
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
# Load image
image = cv2.imread("/content/drive/MyDrive/6/test/road1.jpg")
height, width, channels = image.shape
# Preprocess image for YOLO model
blob = cv2.dnn.blobFromImage(image, scalefactor=0.00392, size=(416, 416), mean=(0, 0, 0), swapRB=True, crop=False)
# Set the input to the YOLO network
net.setInput(blob)
# Get output layer predictions
outs = net.forward(output_layers)
# Initialize lists to store detected objects and their details
class_ids = []
confidences = []
boxes = []
# Process each output layer
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5: # You can adjust this threshold as needed
# 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)
# Non-maximum suppression to eliminate redundant overlapping boxes
indexes = cv2.dnn.NMSBoxes(boxes, confidences, score_threshold=0.5, nms_threshold=0.4)
# Draw bounding boxes on the image
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = classes[class_ids[i]]
confidence = confidences[i]
# Draw rectangle and label
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, f"{label} {confidence:.2f}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Display the result
'''cv2.imshow("Object Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
display(image)'''
import matplotlib.pyplot as plt
plt.imshow(image)
plt.axis('off') # Turn off axis labels
plt.show()
link to model, classes
https://drive.google.com/drive/folders/18KGfkGRmmznAjTBBRSrew6WfEUYdiuF6?usp=sharing
link to test images
https://drive.google.com/drive/folders/1ZwjomDmyZtsKD8Wi3IlwTUl7EkmOTF-M?usp=sharing
Comments
Post a Comment