Advertisement
Botlarakla

Azadov Nadirbek 16 praktika

Dec 4th, 2024
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.53 KB | Source Code | 0 0
  1. #Yolo.py
  2.  
  3. import cv2
  4. import numpy as np
  5.  
  6. # Load YOLO model
  7. yolo_config = 'yolov3.cfg'
  8. yolo_weights = 'yolov3.weights'
  9. labels_path = 'coco.names'
  10.  
  11. # Load class labels
  12. with open(labels_path, 'r') as f:
  13.     classes = [line.strip() for line in f.readlines()]
  14.  
  15. # Initialize YOLO model
  16. net = cv2.dnn.readNet(yolo_weights, yolo_config)
  17.  
  18. # Set backend to GPU if available, otherwise use CPU
  19. net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
  20. net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
  21.  
  22. # Load input image
  23. image_path = 'image.png'
  24. image = cv2.imread(image_path)
  25. if image is None:
  26.     print("Error: Could not read image file. Check the file path.")
  27.     exit()
  28.  
  29. (h, w) = image.shape[:2]
  30.  
  31. # Prepare input blob
  32. blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
  33. net.setInput(blob)
  34.  
  35. # Get YOLO output layers
  36. layer_names = net.getUnconnectedOutLayersNames()
  37. layer_outputs = net.forward(layer_names)
  38.  
  39. # Initialize lists for detections
  40. boxes, confidences, class_ids = [], [], []
  41. for output in layer_outputs:
  42.     for detection in output:
  43.         scores = detection[5:]
  44.         class_id = np.argmax(scores)
  45.         confidence = scores[class_id]
  46.         if confidence > 0.7:  # Modify threshold here (e.g., d=0.7)
  47.             box = detection[0:4] * np.array([w, h, w, h])
  48.             (center_x, center_y, width, height) = box.astype('int')
  49.             x = int(center_x - width / 2)
  50.             y = int(center_y - height / 2)
  51.             boxes.append([x, y, int(width), int(height)])
  52.             confidences.append(float(confidence))
  53.             class_ids.append(class_id)
  54.  
  55. # Perform non-max suppression
  56. indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
  57.  
  58. # Draw bounding boxes and labels
  59. for i in indices.flatten():
  60.     x, y, w, h = boxes[i]
  61.     label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"
  62.     cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
  63.     cv2.putText(image, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
  64.  
  65. # Display results
  66. cv2.imshow("YOLO Object Detection", image)
  67. cv2.waitKey(0)
  68. cv2.destroyAllWindows()
  69.  
  70.  
  71.  
  72. #ssd.py
  73.  
  74. import cv2
  75. import numpy as np
  76.  
  77. # Load SSD model
  78. ssd_prototxt = 'MobileNetSSD_deploy.prototxt'
  79. ssd_model = 'MobileNetSSD_deploy.caffemodel'
  80. labels_path = 'coco.names'
  81.  
  82. # Load class labels
  83. with open(labels_path, 'r') as f:
  84.     classes = [line.strip() for line in f.readlines()]
  85.  
  86. # Initialize SSD model
  87. net = cv2.dnn.readNetFromCaffe(ssd_prototxt, ssd_model)
  88.  
  89. # Load input image
  90. image_path = 'image4.png'
  91. image = cv2.imread(image_path)
  92. if image is None:
  93.     print("Error: Could not read image file. Check the file path.")
  94.     exit()
  95.  
  96. (h, w) = image.shape[:2]
  97.  
  98. # Prepare input blob
  99. blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
  100. net.setInput(blob)
  101.  
  102. # Forward pass to get detections
  103. detections = net.forward()
  104.  
  105. # Post-process detections
  106. for i in range(detections.shape[2]):
  107.     confidence = detections[0, 0, i, 2]
  108.     if confidence > 0.7:  # Modify threshold here (e.g., d=0.7)
  109.         idx = int(detections[0, 0, i, 1])
  110.         box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  111.         (startX, startY, endX, endY) = box.astype('int')
  112.         label = f"{classes[idx]}: {confidence:.2f}"
  113.         cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
  114.         cv2.putText(image, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
  115.  
  116. # Display results
  117. cv2.imshow("SSD Object Detection", image)
  118. cv2.waitKey(0)
  119. cv2.destroyAllWindows()
  120.  
Tags: 16 praktika
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement