imgproc.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. Copyright (c) 2019-present NAVER Corp.
  3. MIT License
  4. """
  5. # -*- coding: utf-8 -*-
  6. import numpy as np
  7. from skimage import io
  8. import cv2
  9. def loadImage(img_file):
  10. img = io.imread(img_file) # RGB order
  11. if img.shape[0] == 2: img = img[0]
  12. if len(img.shape) == 2 : img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
  13. if img.shape[2] == 4: img = img[:,:,:3]
  14. img = np.array(img)
  15. return img
  16. def normalizeMeanVariance(in_img, mean=(0.485, 0.456, 0.406), variance=(0.229, 0.224, 0.225)):
  17. # should be RGB order
  18. img = in_img.copy().astype(np.float32)
  19. img -= np.array([mean[0] * 255.0, mean[1] * 255.0, mean[2] * 255.0], dtype=np.float32)
  20. img /= np.array([variance[0] * 255.0, variance[1] * 255.0, variance[2] * 255.0], dtype=np.float32)
  21. return img
  22. def denormalizeMeanVariance(in_img, mean=(0.485, 0.456, 0.406), variance=(0.229, 0.224, 0.225)):
  23. # should be RGB order
  24. img = in_img.copy()
  25. img *= variance
  26. img += mean
  27. img *= 255.0
  28. img = np.clip(img, 0, 255).astype(np.uint8)
  29. return img
  30. def resize_aspect_ratio(img, square_size, interpolation, mag_ratio=1):
  31. height, width, channel = img.shape
  32. # magnify image size
  33. target_size = mag_ratio * max(height, width)
  34. # set original image size
  35. if target_size > square_size:
  36. target_size = square_size
  37. ratio = target_size / max(height, width)
  38. target_h, target_w = int(height * ratio), int(width * ratio)
  39. proc = cv2.resize(img, (target_w, target_h), interpolation = interpolation)
  40. # make canvas and paste image
  41. target_h32, target_w32 = target_h, target_w
  42. if target_h % 32 != 0:
  43. target_h32 = target_h + (32 - target_h % 32)
  44. if target_w % 32 != 0:
  45. target_w32 = target_w + (32 - target_w % 32)
  46. resized = np.zeros((target_h32, target_w32, channel), dtype=np.float32)
  47. resized[0:target_h, 0:target_w, :] = proc
  48. target_h, target_w = target_h32, target_w32
  49. size_heatmap = (int(target_w/2), int(target_h/2))
  50. return resized, ratio, size_heatmap
  51. def cvt2HeatmapImg(img):
  52. img = (np.clip(img, 0, 1) * 255).astype(np.uint8)
  53. img = cv2.applyColorMap(img, cv2.COLORMAP_JET)
  54. return img