utils.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import cv2
  2. import numpy as np
  3. import imutils
  4. def saturation(img):
  5. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  6. return hsv[:,:,1]
  7. def mean_image(images):
  8. mean = 0
  9. for image in images:
  10. mean += image/len(images)
  11. return mean.astype(np.uint8)
  12. def mean_percent_value(img):
  13. return np.sum(img, dtype=np.int64) / img.size / 255 * 100
  14. def find_food(img, min_food_size, lower_color_boundary, upper_color_boundary, kernel=None):
  15. img = img.copy()
  16. lower = np.array(lower_color_boundary, dtype="uint8")
  17. upper = np.array(upper_color_boundary, dtype="uint8")
  18. mask = cv2.inRange(img, lower, upper)
  19. if kernel is None:
  20. kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
  21. cleaned = mask
  22. cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, kernel)
  23. cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_OPEN, kernel)
  24. cnts = cv2.findContours(cleaned.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  25. cnts = imutils.grab_contours(cnts)
  26. foods = []
  27. mask = np.zeros(img.shape[0:2], np.uint8)
  28. for c in cnts:
  29. (x, y, w, h) = cv2.boundingRect(c)
  30. if w >= min_food_size and h >= min_food_size:
  31. foods.append((x, y, w, h))
  32. cv2.drawContours(mask, [c], -1, 255, cv2.FILLED)
  33. cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 10)
  34. return foods, mask, img
  35. # Set area_ratio to 0 if you want to have the maximum possible blobs.
  36. # Otherwise adding of blobs is break when the next blob to add is smaller than the first blob times the area_ratio
  37. def find_blob(sat_img, max_blob=1, area_ratio=0.8, kernel=None):
  38. blur = cv2.GaussianBlur(sat_img, (5, 5), 0)
  39. thresh = cv2.threshold(blur, 0, 255,
  40. cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  41. if kernel is None:
  42. kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
  43. cleaned = thresh
  44. cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, kernel)
  45. cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_OPEN, kernel)
  46. # Below code will show smoother blob zone but will include holes at well...
  47. contours, hierarchy = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  48. blobs = []
  49. while len(contours) != 0 and len(blobs) < max_blob :
  50. c = max(contours, key=cv2.contourArea)
  51. if len(blobs) != 0 and cv2.contourArea(blobs[0]) * area_ratio >= cv2.contourArea(c) :
  52. break
  53. blobs.append(c)
  54. contours.remove(c)
  55. mask = np.zeros(sat_img.shape, np.uint8)
  56. cv2.drawContours(mask, blobs, -1, 255, cv2.FILLED)
  57. kept_cleaned = cv2.bitwise_and(cleaned, cleaned, mask=mask)
  58. return kept_cleaned