detect.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import argparse
  2. import json
  3. from detection.utils import *
  4. from os.path import splitext, basename, join
  5. def main():
  6. ap = argparse.ArgumentParser()
  7. ap.add_argument("-i", "--input", required=True, help="input image")
  8. ap.add_argument("-s", "--scale", type=float, default=0.10, help="scale images by this factor (default: x0.1)")
  9. ap.add_argument("-c", "--config", type=str, default="config.json",
  10. help="name file to load config (default: config.json)")
  11. ap.add_argument("-o", "--output", type=str, help="give a directory name to save the game files in it")
  12. ap.add_argument("--hide", action='store_true', default=False, help="hide images")
  13. args = ap.parse_args()
  14. with open(args.config, 'r') as file:
  15. config = json.load(file)
  16. orig, blob_mask, blob, food_mask, food_img = detect(args.input, config)
  17. discrete_img, discrete_blob, discrete_food_list = discretize(blob, food_mask, config['Discrete Width'],
  18. config['Discrete Height'])
  19. if args.output is not None:
  20. filename = splitext(basename(args.input))[0]
  21. dir = args.output
  22. save(join(dir, filename), discrete_img, discrete_blob, discrete_food_list)
  23. if not args.hide:
  24. print_results(orig, blob_mask, blob, food_mask, food_img, discrete_img, args.scale)
  25. def detect(input_file, config):
  26. img = cv2.imread(input_file)
  27. height, width, _ = img.shape
  28. aspect_ratio = config["Aspect Ratio"]
  29. height = int(width*aspect_ratio)
  30. """ Resize image to limits in config file """
  31. limits = np.array(config['Limits'])
  32. transform_mat = cv2.getPerspectiveTransform(np.float32(limits), np.float32(
  33. [[0, 0], [width, 0], [width, height], [0, height]]))
  34. img = cv2.warpPerspective(img, transform_mat, (width, height))
  35. """ Prepare upper and lower mask board """
  36. upper_mask = np.zeros(img.shape[0:2], np.uint8)
  37. lower_mask = np.zeros(img.shape[0:2], np.uint8)
  38. upper_mask = cv2.rectangle(upper_mask, (0, 0), (width, int(height/2)), 255, thickness=cv2.FILLED)
  39. lower_mask = cv2.rectangle(lower_mask, (0, int(height / 2)), (width, height), 255, thickness=cv2.FILLED)
  40. """ Find blob """
  41. sat = saturation(img)
  42. # sum = mean_image([satA, satB])
  43. blob_mask = find_blob(sat)
  44. blob = cv2.bitwise_and(img, img, mask=blob_mask)
  45. """ Print blob information """
  46. print("Blob covering:")
  47. print("\t{:.2f}% of the board.".format(mean_percent_value(blob_mask)))
  48. print("\t{:.2f}% of the upper board.".format(
  49. mean_percent_value(cv2.bitwise_and(blob_mask, blob_mask, mask=upper_mask), img_ratio=0.5)))
  50. print("\t{:.2f}% of the lower board.".format(
  51. mean_percent_value(cv2.bitwise_and(blob_mask, blob_mask, mask=lower_mask), img_ratio=0.5)))
  52. """ Find food """
  53. food_list, food_mask, food_img = find_food(img, config['Min Food Size'], config['Low Food Color'], config['High Food Color'])
  54. """ Print food information """
  55. print("Total food discovered: " + str(len(food_list)))
  56. # for i, food in enumerate(food_list):
  57. # print("\tFood N°" + str(i) + ": " + str(food))
  58. return img, blob_mask, blob, food_mask, food_img
  59. def print_results(orig, blob_mask, blob, food_mask, food, discrete, scale=1.0):
  60. padding = 35
  61. nbr_width = 2
  62. nbr_height = 3
  63. font = cv2.FONT_HERSHEY_SIMPLEX
  64. fontsize = 0.45
  65. thickness = 1
  66. scaled_height = int(orig.shape[0]*scale)
  67. scaled_width = int(orig.shape[1]*scale)
  68. pad = np.zeros((scaled_height, padding, orig.shape[2]), dtype=np.uint8)
  69. line_pad = np.zeros((padding, (scaled_width + padding) * nbr_width + padding, orig.shape[2]), dtype=np.uint8)
  70. print_img = cv2.resize(orig, (scaled_width, scaled_height))
  71. middle = ((0, int(scaled_height/2)), (scaled_width, int(scaled_height/2)))
  72. cv2.line(print_img, middle[0], middle[1], (0, 255, 0), thickness=1)
  73. cv2.putText(print_img, 'Mid Line', (middle[0][0] + 5, middle[0][1] - 5),
  74. font, fontsize, (0, 255, 0), thickness, cv2.LINE_AA)
  75. print_blob_mask = cv2.resize(cv2.cvtColor(blob_mask, cv2.COLOR_GRAY2BGR), (scaled_width, scaled_height))
  76. print_blob = cv2.resize(blob, (scaled_width, scaled_height))
  77. print_food_mask = cv2.resize(cv2.cvtColor(food_mask, cv2.COLOR_GRAY2BGR), (scaled_width, scaled_height))
  78. print_food = cv2.resize(food, (scaled_width, scaled_height))
  79. print_discrete = cv2.resize(discrete, (scaled_width, scaled_height))
  80. concat_line1 = np.concatenate((pad, print_img, pad, print_discrete, pad), axis=1)
  81. concat_line2 = np.concatenate((pad, print_blob_mask, pad, print_blob, pad), axis=1)
  82. concat_line3 = np.concatenate((pad, print_food_mask, pad, print_food, pad), axis=1)
  83. aggregate = np.concatenate((line_pad, concat_line1, line_pad, concat_line2, line_pad, concat_line3, line_pad))
  84. cv2.putText(aggregate, 'Original:',
  85. (0 * (scaled_width + padding) + padding + 5, 0 * (scaled_height + padding) + padding - 5),
  86. font, fontsize, (255, 255, 255), thickness, cv2.LINE_AA)
  87. cv2.putText(aggregate, 'Discrete:',
  88. (1 * (scaled_width + padding) + padding + 5, 0 * (scaled_height + padding) + padding - 5),
  89. font, fontsize, (255, 255, 255), thickness, cv2.LINE_AA)
  90. cv2.putText(aggregate, 'Blob Mask:',
  91. (0 * (scaled_width + padding) + padding + 5, 1 * (scaled_height + padding) + padding - 5),
  92. font, fontsize, (255, 255, 255), thickness, cv2.LINE_AA)
  93. cv2.putText(aggregate, 'Blob:',
  94. (1 * (scaled_width + padding) + padding + 5, 1 * (scaled_height + padding) + padding - 5),
  95. font, fontsize, (255, 255, 255), thickness, cv2.LINE_AA)
  96. cv2.putText(aggregate, 'Food Mask:',
  97. (0 * (scaled_width + padding) + padding + 5, 2 * (scaled_height + padding) + padding - 5),
  98. font, fontsize, (255, 255, 255), thickness, cv2.LINE_AA)
  99. cv2.putText(aggregate, 'Food Regions:',
  100. (1 * (scaled_width + padding) + padding + 5, 2 * (scaled_height + padding) + padding - 5),
  101. font, fontsize, (255, 255, 255), thickness, cv2.LINE_AA)
  102. cv2.imshow("Results", aggregate)
  103. print("\nPress any key...")
  104. cv2.waitKey(0)
  105. def discretize(blob_img, food_mask, width, height):
  106. img_height, img_width, _ = blob_img.shape
  107. discrete_blob = cv2.resize(blob_img, (width, height), interpolation=cv2.INTER_NEAREST)
  108. discrete_food = cv2.resize(food_mask, (width, height), interpolation=cv2.INTER_NEAREST)
  109. discrete_food_list = []
  110. for x in range(height):
  111. for y in range(width):
  112. if discrete_food[x, y] != 0:
  113. discrete_food_list.append((y, x))
  114. height, width, _ = discrete_blob.shape
  115. discrete_blob = cv2.cvtColor(discrete_blob, cv2.COLOR_BGR2GRAY)
  116. # If discrete blob has to be connected, used this :
  117. # contours, hierarchy = cv2.findContours(discrete_blob, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  118. # c = max(contours, key=cv2.contourArea)
  119. # mask = np.zeros(discrete_blob.shape, np.uint8)
  120. # cv2.drawContours(mask, [c], -1, 255, cv2.FILLED)
  121. # discrete_blob = cv2.bitwise_and(discrete_blob, discrete_blob, mask=mask)
  122. discrete_blob_bgr = cv2.cvtColor(discrete_blob, cv2.COLOR_GRAY2BGR)
  123. discrete_img = cv2.resize(discrete_blob_bgr, (0, 0), fx=10, fy=10, interpolation=cv2.INTER_NEAREST)
  124. for (x, y) in discrete_food_list:
  125. cv2.rectangle(discrete_img, (x * 10, y * 10), ((x + 1) * 10, (y + 1) * 10), (0, 255, 0), thickness=cv2.FILLED)
  126. if discrete_blob[y, x] != 0:
  127. cv2.drawMarker(discrete_img, (x * 10 + 5, y * 10 + 5), (255, 255, 255), thickness=2, markerSize=9,
  128. markerType=cv2.MARKER_TILTED_CROSS)
  129. return discrete_img, discrete_blob, discrete_food_list
  130. def save(filename, discrete_img, discrete_blob, discrete_food_list):
  131. height, width = discrete_blob.shape
  132. board_str = str(width) + ' ' + str(height) + '\n'
  133. discrete_food = np.zeros(discrete_blob.shape, dtype=bool)
  134. for (x, y) in discrete_food_list:
  135. discrete_food[y, x] = True
  136. for x in range(height):
  137. for y in range(width):
  138. board_str += "{:d},{:d},{} ".format(discrete_blob[x, y] != 0, discrete_food[x,y], discrete_blob[x, y])
  139. board_str = board_str[:-1]
  140. board_str += "\n"
  141. board_str = board_str[:-1]
  142. with open(filename + ".board", 'w') as board_file:
  143. board_file.write(board_str)
  144. cv2.imwrite(filename + ".jpg", discrete_img)
  145. if __name__ == "__main__":
  146. main()