dress_to_correct.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import cv2
  2. import math
  3. import numpy as np
  4. import os
  5. # create_correct ===============================================================
  6. # return:
  7. # (<Boolean> True/False), depending on the transformation process
  8. def create_correct(cv_dress):
  9. #Production dir:
  10. return correct_color(cv_dress, 5)
  11. # correct_color ==============================================================================
  12. # return:
  13. # <RGB> image corrected
  14. def correct_color(img, percent):
  15. assert img.shape[2] == 3
  16. assert percent > 0 and percent < 100
  17. half_percent = percent / 200.0
  18. channels = cv2.split(img)
  19. out_channels = []
  20. for channel in channels:
  21. assert len(channel.shape) == 2
  22. # find the low and high precentile values (based on the input percentile)
  23. height, width = channel.shape
  24. vec_size = width * height
  25. flat = channel.reshape(vec_size)
  26. assert len(flat.shape) == 1
  27. flat = np.sort(flat)
  28. n_cols = flat.shape[0]
  29. low_val = flat[math.floor(n_cols * half_percent)]
  30. high_val = flat[math.ceil( n_cols * (1.0 - half_percent))]
  31. # saturate below the low percentile and above the high percentile
  32. thresholded = apply_threshold(channel, low_val, high_val)
  33. # scale the channel
  34. normalized = cv2.normalize(thresholded, thresholded.copy(), 0, 255, cv2.NORM_MINMAX)
  35. out_channels.append(normalized)
  36. return cv2.merge(out_channels)
  37. #Color correction utils
  38. def apply_threshold(matrix, low_value, high_value):
  39. low_mask = matrix < low_value
  40. matrix = apply_mask(matrix, low_mask, low_value)
  41. high_mask = matrix > high_value
  42. matrix = apply_mask(matrix, high_mask, high_value)
  43. return matrix
  44. #Color correction utils
  45. def apply_mask(matrix, mask, fill_value):
  46. masked = np.ma.array(matrix, mask=mask, fill_value=fill_value)
  47. return masked.filled()