You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
2.7 KiB

5 years ago
5 years ago
  1. import cv2
  2. def detect(input, output):
  3. classes = {0: 'background',
  4. 1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 5: 'airplane', 6: 'bus',
  5. 7: 'train', 8: 'truck', 9: 'boat', 10: 'traffic light', 11: 'fire hydrant',
  6. 13: 'stop sign', 14: 'parking meter', 15: 'bench', 16: 'bird', 17: 'cat',
  7. 18: 'dog', 19: 'horse', 20: 'sheep', 21: 'cow', 22: 'elephant', 23: 'bear',
  8. 24: 'zebra', 25: 'giraffe', 27: 'backpack', 28: 'umbrella', 31: 'handbag',
  9. 32: 'tie', 33: 'suitcase', 34: 'frisbee', 35: 'skis', 36: 'snowboard',
  10. 37: 'sports ball', 38: 'kite', 39: 'baseball bat', 40: 'baseball glove',
  11. 41: 'skateboard', 42: 'surfboard', 43: 'tennis racket', 44: 'bottle',
  12. 46: 'wine glass', 47: 'cup', 48: 'fork', 49: 'knife', 50: 'spoon',
  13. 51: 'bowl', 52: 'banana', 53: 'apple', 54: 'sandwich', 55: 'orange',
  14. 56: 'broccoli', 57: 'carrot', 58: 'hot dog', 59: 'pizza', 60: 'donut',
  15. 61: 'cake', 62: 'chair', 63: 'couch', 64: 'potted plant', 65: 'bed',
  16. 67: 'dining table', 70: 'toilet', 72: 'tv', 73: 'laptop', 74: 'mouse',
  17. 75: 'remote', 76: 'keyboard', 77: 'cell phone', 78: 'microwave', 79: 'oven',
  18. 80: 'toaster', 81: 'sink', 82: 'refrigerator', 84: 'book', 85: 'clock',
  19. 86: 'vase', 87: 'scissors', 88: 'teddy bear', 89: 'hair drier', 90: 'toothbrush'}
  20. # Load a model imported from Tensorflow
  21. tensorflowNet = cv2.dnn.readNetFromTensorflow('./model/frozen_inference_graph.pb', './model/graph.pbtxt')
  22. # Input image
  23. img = cv2.imread(input)
  24. rows, cols, channels = img.shape
  25. # Use the given image as input, which needs to be blob(s).
  26. tensorflowNet.setInput(cv2.dnn.blobFromImage(img, size=(300, 300), swapRB=True, crop=False))
  27. # Runs a forward pass to compute the net output
  28. networkOutput = tensorflowNet.forward()
  29. # Loop on the outputs
  30. for detection in networkOutput[0,0]:
  31. score = float(detection[2])
  32. if score > 0.2:
  33. left = detection[3] * cols
  34. top = detection[4] * rows
  35. right = detection[5] * cols
  36. bottom = detection[6] * rows
  37. #draw a red rectangle around detected objects
  38. cv2.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (0, 0, 255), thickness=2)
  39. #draw category name in top left of rectangle
  40. cv2.putText(img, classes[int(detection[1])], (int(left), int(top-4)), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2, 8)
  41. cv2.imwrite(output, img)
  42. # Show the image with a rectagle surrounding the detected objects