yolov3.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import cv2
  2. import numpy as np
  3. # Load yolo
  4. def load_yolo():
  5. net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
  6. classes = []
  7. with open("coco.names", "r") as f:
  8. classes = [line.strip() for line in f.readlines()]
  9. output_layers = [layer_name for layer_name in net.getUnconnectedOutLayersNames()]
  10. colors = np.random.uniform(0, 255, size=(len(classes), 3))
  11. return net, classes, colors, output_layers
  12. def load_image(img_path):
  13. # image loading
  14. img = cv2.imread(img_path)
  15. img = cv2.resize(img, None, fx=0.4, fy=0.4)
  16. height, width, channels = img.shape
  17. return img, height, width, channels
  18. def start_webcam():
  19. cap = cv2.VideoCapture(0)
  20. return cap
  21. def display_blob(blob):
  22. """
  23. Three images each for RED, GREEN, BLUE channel
  24. """
  25. for b in blob:
  26. for n, imgb in enumerate(b):
  27. cv2.imshow(str(n), imgb)
  28. def detect_objects_yolo(img, net, outputLayers):
  29. blob = cv2.dnn.blobFromImage(img, scalefactor=0.00392, size=(320, 320), mean=(0, 0, 0), swapRB=True, crop=False)
  30. net.setInput(blob)
  31. outputs = net.forward(outputLayers)
  32. # print(outputs)
  33. # for i, out in enumerate(outputs):
  34. # print(i, np.array(out).shape)
  35. return blob, outputs
  36. def get_box_dimensions_yolo(outputs, height, width):
  37. boxes = []
  38. confs = []
  39. class_ids = []
  40. for output in outputs:
  41. for detect in output:
  42. scores = detect[5:]
  43. # print('detect', scores)
  44. class_id = np.argmax(scores)
  45. conf = scores[class_id]
  46. if conf > 0.3:
  47. center_x = int(detect[0] * width)
  48. center_y = int(detect[1] * height)
  49. w = int(detect[2] * width)
  50. h = int(detect[3] * height)
  51. x = int(center_x - w / 2)
  52. y = int(center_y - h / 2)
  53. boxes.append([x, y, w, h])
  54. # print(boxes)
  55. confs.append(float(conf))
  56. class_ids.append(class_id)
  57. return boxes, confs, class_ids
  58. def draw_labels_yolo(boxes, confs, colors, class_ids, classes, img):
  59. indexes = cv2.dnn.NMSBoxes(boxes, confs, 0.5, 0.4)
  60. font = cv2.FONT_HERSHEY_PLAIN
  61. for i in range(len(boxes)):
  62. if i in indexes:
  63. x, y, w, h = boxes[i]
  64. label = str(classes[class_ids[i]])
  65. color = colors[i]
  66. cv2.rectangle(img, (x, y), (x + w, y + h), color, 5)
  67. cv2.putText(img, label, (x, y - 5), font, 5, color, 5)
  68. return img
  69. def image_detect_yolo(img_path):
  70. model, classes, colors, output_layers = load_yolo()
  71. image, height, width, channels = load_image(img_path)
  72. blob, outputs = detect_objects_yolo(image, model, output_layers)
  73. # print(outputs)
  74. boxes, confs, class_ids = get_box_dimensions_yolo(outputs, height, width)
  75. image = draw_labels_yolo(boxes, confs, colors, class_ids, classes, image)
  76. return image
  77. cv2.destroyAllWindows()