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.

139 lines
4.7 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. from flask import Flask, request
  2. from flask_restful import Resource, Api, abort
  3. import json
  4. import io
  5. import base64
  6. from PIL import Image
  7. import sys
  8. import datetime
  9. import cv2
  10. if sys.platform == "win32":
  11. import tensorflow as tf
  12. import numpy as np
  13. import pickle
  14. sys.path.insert(0, r'C:\Users\Tednokent01\Downloads\MyCity\traffic_analyzer')
  15. from utils import label_map_util
  16. from utils import visualization_utils as vis_util
  17. app = Flask(__name__)
  18. api = Api(app)
  19. with open("modules/databases/complaints.json","r") as f:
  20. complaints = json.load(f)
  21. if sys.platform == "win32":
  22. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  23. PATH_TO_CKPT = 'modules/trainedModels/ssd_mobilenet_RoadDamageDetector.pb'
  24. # List of the strings that is used to add correct label for each box.
  25. PATH_TO_LABELS = 'modules/trainedModels/crack_label_map.pbtxt'
  26. NUM_CLASSES = 8
  27. detection_graph = tf.Graph()
  28. with detection_graph.as_default():
  29. od_graph_def = tf.GraphDef()
  30. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  31. serialized_graph = fid.read()
  32. od_graph_def.ParseFromString(serialized_graph)
  33. tf.import_graph_def(od_graph_def, name='')
  34. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  35. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  36. category_index = label_map_util.create_category_index(categories)
  37. def load_image_into_numpy_array(image):
  38. (im_width, im_height) = image.size
  39. return np.array(image.getdata()).reshape(
  40. (im_height, im_width, 3)).astype(np.uint8)
  41. def process_img(img_base64):
  42. if sys.platform == "win32":
  43. img = Image.open(io.BytesIO(base64.b64decode(img_base64)))
  44. with detection_graph.as_default():
  45. with tf.Session(graph=detection_graph) as sess:
  46. # Definite input and output Tensors for detection_graph
  47. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  48. # Each box represents a part of the image where a particular object was detected.
  49. detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  50. # Each score represent how level of confidence for each of the objects.
  51. # Score is shown on the result image, together with the class label.
  52. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
  53. detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
  54. num_detections = detection_graph.get_tensor_by_name('num_detections:0')
  55. # the array based representation of the image will be used later in order to prepare the
  56. # result image with boxes and labels on it.
  57. image_np = load_image_into_numpy_array(img)
  58. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  59. image_np_expanded = np.expand_dims(image_np, axis=0)
  60. # Actual detection.
  61. (boxes, scores, classes, num) = sess.run(
  62. [detection_boxes, detection_scores, detection_classes, num_detections],
  63. feed_dict={image_tensor: image_np_expanded})
  64. # Visualization of the results of a detection.
  65. vis_util.visualize_boxes_and_labels_on_image_array(
  66. image_np,
  67. np.squeeze(boxes),
  68. np.squeeze(classes).astype(np.int32),
  69. np.squeeze(scores),
  70. category_index,
  71. min_score_thresh=0.3,
  72. use_normalized_coordinates=True,
  73. line_thickness=8)
  74. cv2.imwrite('cv222.png', image_np)
  75. output_dict = {'detection_classes': classes, 'detection_scores': scores[0]}
  76. defects = []
  77. for i in output_dict['detection_classes']:
  78. index = np.where(output_dict['detection_classes'] == i)[0][0]
  79. score = output_dict['detection_scores'][index]
  80. if score > 0.3:
  81. defects.append(score)
  82. priority = sum(defects) // 0.5
  83. if priority > 10:
  84. priority = 10
  85. return base64.b64encode(pickle.dumps(image_np)).decode('ascii'),priority,defects
  86. return img_base64, 7,["unprocessed"]
  87. class Complaint(Resource):
  88. def post(self):
  89. complaint = {}
  90. args = request.form.to_dict()
  91. complaint = args
  92. complaint["response"] = {"status":False}
  93. img_process,priority,tags = process_img(complaint["img"])
  94. complaint["img"] = img_process
  95. complaint["response"]["priority"] = str(priority)
  96. complaint["tags"] = list(map(str, tags))
  97. complaint["datetime"] = datetime.datetime.now().strftime('%b-%d-%I:%M %p-%G')
  98. try:
  99. complaints[complaint["id"]].append(complaint)
  100. except KeyError:
  101. complaints[complaint["id"]] = [complaint]
  102. del complaints[complaint["id"]][-1]["id"]
  103. with open('modules/databases/complaints.json', 'w') as complaints_file:
  104. json.dump(complaints, complaints_file, indent=4)
  105. class Complaints(Resource):
  106. def post(self):
  107. id = request.form["id"]
  108. return complaints[id]
  109. class ComplaintsAdmin(Resource):
  110. def get(self): return complaints