You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

blur.py 7.2 kB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # Copyright 2022 Huawei Technologies Co., Ltd
  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. """
  15. Image Blur
  16. """
  17. import numpy as np
  18. import cv2
  19. from mindarmour.natural_robustness.transform.image.natural_perturb import _NaturalPerturb
  20. from mindarmour.utils._check_param import check_param_multi_types, check_int_positive, check_param_type
  21. from mindarmour.utils.logger import LogUtil
  22. LOGGER = LogUtil.get_instance()
  23. TAG = 'Image Blur'
  24. class GaussianBlur(_NaturalPerturb):
  25. """
  26. Blurs the image using Gaussian blur filter.
  27. Args:
  28. ksize (int): Size of gaussian kernel, this value must be non-negnative. Default: 2.
  29. auto_param (bool): Auto selected parameters. Selected parameters will preserve semantics of image.
  30. Default: False.
  31. Examples:
  32. >>> import cv2
  33. >>> img = cv2.imread('1.png')
  34. >>> img = np.array(img)
  35. >>> ksize = 5
  36. >>> trans = GaussianBlur(ksize)
  37. >>> dst = trans(img)
  38. """
  39. def __init__(self, ksize=2, auto_param=False):
  40. super(GaussianBlur, self).__init__()
  41. ksize = check_int_positive('ksize', ksize)
  42. if auto_param:
  43. ksize = 2 * np.random.randint(0, 5) + 1
  44. else:
  45. ksize = 2 * ksize + 1
  46. self.ksize = (ksize, ksize)
  47. def __call__(self, image):
  48. """
  49. Transform the image.
  50. Args:
  51. image (numpy.ndarray): Original image to be transformed.
  52. Returns:
  53. numpy.ndarray, transformed image.
  54. """
  55. ori_dtype = image.dtype
  56. _, chw, normalized, gray3dim, image = self._check(image)
  57. new_img = cv2.GaussianBlur(image, self.ksize, 0)
  58. new_img = self._original_format(new_img, chw, normalized, gray3dim)
  59. return new_img.astype(ori_dtype)
  60. class MotionBlur(_NaturalPerturb):
  61. """
  62. Motion blur for a given image.
  63. Args:
  64. degree (int): Degree of blur. This value must be positive. Suggested value range in [1, 15]. Default: 5.
  65. angle (union[float, int]): Direction of motion blur. Angle=0 means up and down motion blur. Angle is
  66. counterclockwise. Default: 45.
  67. auto_param (bool): Auto selected parameters. Selected parameters will preserve semantics of image.
  68. Default: False.
  69. Examples:
  70. >>> import cv2
  71. >>> img = cv2.imread('1.png')
  72. >>> img = np.array(img)
  73. >>> angle = 0
  74. >>> degree = 5
  75. >>> trans = MotionBlur(degree=degree, angle=angle)
  76. >>> new_img = trans(img)
  77. """
  78. def __init__(self, degree=5, angle=45, auto_param=False):
  79. super(MotionBlur, self).__init__()
  80. self.degree = check_int_positive('degree', degree)
  81. self.degree = check_param_multi_types('degree', degree, [float, int])
  82. auto_param = check_param_type('auto_param', auto_param, bool)
  83. if auto_param:
  84. self.degree = np.random.randint(1, 5)
  85. self.angle = np.random.uniform(0, 360)
  86. else:
  87. self.angle = angle - 45
  88. def __call__(self, image):
  89. """
  90. Motion blur for a given image.
  91. Args:
  92. image (numpy.ndarray): Original image.
  93. Returns:
  94. numpy.ndarray, image after motion blur.
  95. """
  96. ori_dtype = image.dtype
  97. _, chw, normalized, gray3dim, image = self._check(image)
  98. matrix = cv2.getRotationMatrix2D((self.degree / 2, self.degree / 2), self.angle, 1)
  99. motion_blur_kernel = np.diag(np.ones(self.degree))
  100. motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, matrix, (self.degree, self.degree))
  101. motion_blur_kernel = motion_blur_kernel / self.degree
  102. blurred = cv2.filter2D(image, -1, motion_blur_kernel)
  103. # convert to uint8
  104. cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
  105. blurred = self._original_format(blurred, chw, normalized, gray3dim)
  106. return blurred.astype(ori_dtype)
  107. class GradientBlur(_NaturalPerturb):
  108. """
  109. Gradient blur.
  110. Args:
  111. point (union[tuple, list]): 2D coordinate of the Blur center point.
  112. kernel_num (int): Number of blur kernels. Suggested value range in [1, 8]. Default: 3.
  113. center (bool): Blurred or clear at the center of a specified point.
  114. auto_param (bool): Auto selected parameters. Selected parameters will preserve semantics of image.
  115. Default: False.
  116. Examples:
  117. >>> import cv2
  118. >>> img = cv2.imread('xx.png')
  119. >>> img = np.array(img)
  120. >>> number = 5
  121. >>> h, w = img.shape[:2]
  122. >>> point = (int(h / 5), int(w / 5))
  123. >>> center = True
  124. >>> trans = GradientBlur(point, number, center)
  125. >>> new_img = trans(img)
  126. """
  127. def __init__(self, point, kernel_num=3, center=True, auto_param=False):
  128. super(GradientBlur).__init__()
  129. point = check_param_multi_types('point', point, [list, tuple])
  130. self.auto_param = check_param_type('auto_param', auto_param, bool)
  131. self.point = tuple(point)
  132. self.kernel_num = check_int_positive('kernel_num', kernel_num)
  133. self.center = check_param_type('center', center, bool)
  134. def _auto_param(self, h, w):
  135. self.point = (int(np.random.uniform(0, h)), int(np.random.uniform(0, w)))
  136. self.kernel_num = np.random.randint(1, 6)
  137. self.center = np.random.choice([True, False])
  138. def __call__(self, image):
  139. """
  140. Args:
  141. image (numpy.ndarray): Original image.
  142. Returns:
  143. numpy.ndarray, gradient blurred image.
  144. """
  145. ori_dtype = image.dtype
  146. _, chw, normalized, gray3dim, image = self._check(image)
  147. w, h = image.shape[:2]
  148. if self.auto_param:
  149. self._auto_param(h, w)
  150. mask = np.zeros(image.shape, dtype=np.uint8)
  151. masks = []
  152. radius = max(w - self.point[0], self.point[0], h - self.point[1], self.point[1])
  153. radius = int(radius / self.kernel_num)
  154. for i in range(self.kernel_num):
  155. circle = cv2.circle(mask.copy(), self.point, radius * (1 + i), (1, 1, 1), -1)
  156. masks.append(circle)
  157. blurs = []
  158. for i in range(3, 3 + 2 * self.kernel_num, 2):
  159. ksize = (i, i)
  160. blur = cv2.GaussianBlur(image, ksize, 0)
  161. blurs.append(blur)
  162. dst = image.copy()
  163. if self.center:
  164. for i in range(self.kernel_num):
  165. dst = masks[i] * dst + (1 - masks[i]) * blurs[i]
  166. else:
  167. for i in range(self.kernel_num - 1, -1, -1):
  168. dst = masks[i] * blurs[self.kernel_num - 1 - i] + (1 - masks[i]) * dst
  169. dst = self._original_format(dst, chw, normalized, gray3dim)
  170. return dst.astype(ori_dtype)

MindArmour关注AI的安全和隐私问题。致力于增强模型的安全可信、保护用户的数据隐私。主要包含3个模块:对抗样本鲁棒性模块、Fuzz Testing模块、隐私保护与评估模块。 对抗样本鲁棒性模块 对抗样本鲁棒性模块用于评估模型对于对抗样本的鲁棒性,并提供模型增强方法用于增强模型抗对抗样本攻击的能力,提升模型鲁棒性。对抗样本鲁棒性模块包含了4个子模块:对抗样本的生成、对抗样本的检测、模型防御、攻防评估。