utils.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import cv2
  15. import numpy as np
  16. class DecodeImage(object):
  17. def __init__(self, to_rgb=True):
  18. self.to_rgb = to_rgb
  19. def __call__(self, img):
  20. data = np.frombuffer(img, dtype='uint8')
  21. img = cv2.imdecode(data, 1)
  22. if self.to_rgb:
  23. assert img.shape[2] == 3, 'invalid shape of image[%s]' % (
  24. img.shape)
  25. img = img[:, :, ::-1]
  26. return img
  27. class ResizeImage(object):
  28. def __init__(self, resize_short=None, interpolation=1):
  29. self.resize_short = resize_short
  30. self.interpolation = interpolation
  31. def __call__(self, img):
  32. img_h, img_w = img.shape[:2]
  33. percent = float(self.resize_short) / min(img_w, img_h)
  34. w = int(round(img_w * percent))
  35. h = int(round(img_h * percent))
  36. return cv2.resize(img, (w, h), interpolation=self.interpolation)
  37. class CropImage(object):
  38. def __init__(self, size):
  39. if type(size) is int:
  40. self.size = (size, size)
  41. else:
  42. self.size = size
  43. def __call__(self, img):
  44. w, h = self.size
  45. img_h, img_w = img.shape[:2]
  46. w_start = (img_w - w) // 2
  47. h_start = (img_h - h) // 2
  48. w_end = w_start + w
  49. h_end = h_start + h
  50. return img[h_start:h_end, w_start:w_end, :]
  51. class NormalizeImage(object):
  52. def __init__(self, scale=None, mean=None, std=None):
  53. self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
  54. mean = mean if mean is not None else [0.485, 0.456, 0.406]
  55. std = std if std is not None else [0.229, 0.224, 0.225]
  56. shape = (1, 1, 3)
  57. self.mean = np.array(mean).reshape(shape).astype('float32')
  58. self.std = np.array(std).reshape(shape).astype('float32')
  59. def __call__(self, img):
  60. return (img.astype('float32') * self.scale - self.mean) / self.std
  61. class ToTensor(object):
  62. def __init__(self):
  63. pass
  64. def __call__(self, img):
  65. img = img.transpose((2, 0, 1))
  66. return img