/ on_dataset.py
on_dataset.py
1 import os 2 import cv2 3 import numpy as np 4 5 # Load YOLO 6 net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg") 7 classes = [] 8 with open("coco.names", "r") as f: 9 classes = [line.strip() for line in f.readlines()] 10 11 layer_names = net.getLayerNames() 12 output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] 13 14 # Load dataset 15 dataset_path = r"YOUR_PATH" 16 image_files = [file for file in os.listdir(dataset_path) if file.endswith((".jpg", ".jpeg"))] 17 18 # Loop through images in the dataset 19 for image_file in image_files: 20 # Read image 21 image = cv2.imread(os.path.join(dataset_path, image_file)) 22 if image is None: 23 print(f"Error: Unable to read image file '{image_file}'. Skipping...") 24 continue 25 height, width, channels = image.shape 26 27 # Detecting objects 28 blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False) 29 net.setInput(blob) 30 outs = net.forward(output_layers) 31 32 # Showing information on the screen 33 class_ids = [] 34 confidences = [] 35 boxes = [] 36 for out in outs: 37 for detection in out: 38 scores = detection[5:] 39 class_id = np.argmax(scores) 40 confidence = scores[class_id] 41 if confidence > 0.5: # Confidence threshold 42 # Object detected 43 center_x = int(detection[0] * width) 44 center_y = int(detection[1] * height) 45 w = int(detection[2] * width) 46 h = int(detection[3] * height) 47 48 # Rectangle coordinates 49 x = int(center_x - w / 2) 50 y = int(center_y - h / 2) 51 52 boxes.append([x, y, w, h]) 53 confidences.append(float(confidence)) 54 class_ids.append(class_id) 55 56 indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # Non-maximum suppression 57 58 font = cv2.FONT_HERSHEY_PLAIN 59 for i in range(len(boxes)): 60 if i in indexes: 61 x, y, w, h = boxes[i] 62 label = str(classes[class_ids[i]]) 63 color = (255, 0, 0) 64 cv2.rectangle(image, (x, y), (x + w, y + h), color, 2) 65 cv2.putText(image, label, (x, y + 30), font, 3, color, 3) 66 print(f"Object detected: {label} (Confidence: {confidences[i]})") 67 68 # Show image 69 #cv2.imshow("Image", image) 70 #cv2.waitKey(0) 71 #cv2.destroyAllWindows()