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.

test_adjustgamma.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # Copyright 2021 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. """
  16. Testing AdjustGamma op in DE
  17. """
  18. import numpy as np
  19. from numpy.testing import assert_allclose
  20. import PIL
  21. import mindspore.dataset as ds
  22. import mindspore.dataset.transforms.py_transforms
  23. import mindspore.dataset.vision.py_transforms as F
  24. import mindspore.dataset.vision.c_transforms as C
  25. from mindspore import log as logger
  26. DATA_DIR = "../data/dataset/testImageNetData/train/"
  27. MNIST_DATA_DIR = "../data/dataset/testMnistData"
  28. DATA_DIR_2 = ["../data/dataset/test_tf_file_3_images/train-0000-of-0001.data"]
  29. SCHEMA_DIR = "../data/dataset/test_tf_file_3_images/datasetSchema.json"
  30. def generate_numpy_random_rgb(shape):
  31. """
  32. Only generate floating points that are fractions like n / 256, since they
  33. are RGB pixels. Some low-precision floating point types in this test can't
  34. handle arbitrary precision floating points well.
  35. """
  36. return np.random.randint(0, 256, shape) / 255.
  37. def test_adjust_gamma_c_eager():
  38. # Eager 3-channel
  39. rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.float32)
  40. img_in = rgb_flat.reshape((8, 8, 3))
  41. adjustgamma_op = C.AdjustGamma(10, 1)
  42. img_out = adjustgamma_op(img_in)
  43. assert img_out is not None
  44. def test_adjust_gamma_py_eager():
  45. # Eager 3-channel
  46. rgb_flat = generate_numpy_random_rgb((64, 3)).astype(np.uint8)
  47. img_in = PIL.Image.fromarray(rgb_flat.reshape((8, 8, 3)))
  48. adjustgamma_op = F.AdjustGamma(10, 1)
  49. img_out = adjustgamma_op(img_in)
  50. assert img_out is not None
  51. def test_adjust_gamma_c_eager_gray():
  52. # Eager 3-channel
  53. rgb_flat = generate_numpy_random_rgb((64, 1)).astype(np.float32)
  54. img_in = rgb_flat.reshape((8, 8))
  55. adjustgamma_op = C.AdjustGamma(10, 1)
  56. img_out = adjustgamma_op(img_in)
  57. assert img_out is not None
  58. def test_adjust_gamma_py_eager_gray():
  59. # Eager 3-channel
  60. rgb_flat = generate_numpy_random_rgb((64, 1)).astype(np.uint8)
  61. img_in = PIL.Image.fromarray(rgb_flat.reshape((8, 8)))
  62. adjustgamma_op = F.AdjustGamma(10, 1)
  63. img_out = adjustgamma_op(img_in)
  64. assert img_out is not None
  65. def test_adjust_gamma_invalid_gamma_param_c():
  66. """
  67. Test AdjustGamma C Op with invalid ignore parameter
  68. """
  69. logger.info("Test AdjustGamma C Op with invalid ignore parameter")
  70. try:
  71. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  72. data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])],
  73. input_columns=["image"])
  74. # invalid gamma
  75. data_set = data_set.map(operations=C.AdjustGamma(gamma=-10.0, gain=1.0),
  76. input_columns="image")
  77. except ValueError as error:
  78. logger.info("Got an exception in AdjustGamma: {}".format(str(error)))
  79. assert "Input is not within the required interval of " in str(error)
  80. try:
  81. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  82. data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])],
  83. input_columns=["image"])
  84. # invalid gamma
  85. data_set = data_set.map(operations=C.AdjustGamma(gamma=[1, 2], gain=1.0),
  86. input_columns="image")
  87. except TypeError as error:
  88. logger.info("Got an exception in AdjustGamma: {}".format(str(error)))
  89. assert "is not of type [<class 'float'>, <class 'int'>], but got" in str(error)
  90. def test_adjust_gamma_invalid_gamma_param_py():
  91. """
  92. Test AdjustGamma python Op with invalid ignore parameter
  93. """
  94. logger.info("Test AdjustGamma python Op with invalid ignore parameter")
  95. try:
  96. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  97. trans = mindspore.dataset.transforms.py_transforms.Compose([
  98. F.Decode(),
  99. F.Resize((224, 224)),
  100. F.AdjustGamma(gamma=-10.0),
  101. F.ToTensor()
  102. ])
  103. data_set = data_set.map(operations=[trans], input_columns=["image"])
  104. except ValueError as error:
  105. logger.info("Got an exception in AdjustGamma: {}".format(str(error)))
  106. assert "Input is not within the required interval of " in str(error)
  107. try:
  108. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  109. trans = mindspore.dataset.transforms.py_transforms.Compose([
  110. F.Decode(),
  111. F.Resize((224, 224)),
  112. F.AdjustGamma(gamma=[1, 2]),
  113. F.ToTensor()
  114. ])
  115. data_set = data_set.map(operations=[trans], input_columns=["image"])
  116. except TypeError as error:
  117. logger.info("Got an exception in AdjustGamma: {}".format(str(error)))
  118. assert "is not of type [<class 'float'>, <class 'int'>], but got" in str(error)
  119. def test_adjust_gamma_invalid_gain_param_c():
  120. """
  121. Test AdjustGamma C Op with invalid gain parameter
  122. """
  123. logger.info("Test AdjustGamma C Op with invalid gain parameter")
  124. try:
  125. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  126. data_set = data_set.map(operations=[C.Decode(), C.Resize((224, 224)), lambda img: np.array(img[:, :, 0])],
  127. input_columns=["image"])
  128. # invalid gain
  129. data_set = data_set.map(operations=C.AdjustGamma(gamma=10.0, gain=[1, 10]),
  130. input_columns="image")
  131. except TypeError as error:
  132. logger.info("Got an exception in AdjustGamma: {}".format(str(error)))
  133. assert "is not of type [<class 'float'>, <class 'int'>], but got " in str(error)
  134. def test_adjust_gamma_invalid_gain_param_py():
  135. """
  136. Test AdjustGamma python Op with invalid gain parameter
  137. """
  138. logger.info("Test AdjustGamma python Op with invalid gain parameter")
  139. try:
  140. data_set = ds.ImageFolderDataset(dataset_dir=DATA_DIR, shuffle=False)
  141. trans = mindspore.dataset.transforms.py_transforms.Compose([
  142. F.Decode(),
  143. F.Resize((224, 224)),
  144. F.AdjustGamma(gamma=10.0, gain=[1, 10]),
  145. F.ToTensor()
  146. ])
  147. data_set = data_set.map(operations=[trans], input_columns=["image"])
  148. except TypeError as error:
  149. logger.info("Got an exception in AdjustGamma: {}".format(str(error)))
  150. assert "is not of type [<class 'float'>, <class 'int'>], but got " in str(error)
  151. def test_adjust_gamma_pipeline_c():
  152. """
  153. Test AdjustGamma C Op Pipeline
  154. """
  155. # First dataset
  156. transforms1 = [C.Decode(), C.Resize([64, 64])]
  157. transforms1 = mindspore.dataset.transforms.py_transforms.Compose(
  158. transforms1)
  159. ds1 = ds.TFRecordDataset(DATA_DIR_2,
  160. SCHEMA_DIR,
  161. columns_list=["image"],
  162. shuffle=False)
  163. ds1 = ds1.map(operations=transforms1, input_columns=["image"])
  164. # Second dataset
  165. transforms2 = [
  166. C.Decode(),
  167. C.Resize([64, 64]),
  168. C.AdjustGamma(1.0, 1.0)
  169. ]
  170. transform2 = mindspore.dataset.transforms.py_transforms.Compose(
  171. transforms2)
  172. ds2 = ds.TFRecordDataset(DATA_DIR_2,
  173. SCHEMA_DIR,
  174. columns_list=["image"],
  175. shuffle=False)
  176. ds2 = ds2.map(operations=transform2, input_columns=["image"])
  177. num_iter = 0
  178. for data1, data2 in zip(ds1.create_dict_iterator(num_epochs=1),
  179. ds2.create_dict_iterator(num_epochs=1)):
  180. num_iter += 1
  181. ori_img = data1["image"].asnumpy()
  182. cvt_img = data2["image"].asnumpy()
  183. assert_allclose(ori_img.flatten(),
  184. cvt_img.flatten(),
  185. rtol=1e-5,
  186. atol=0)
  187. assert ori_img.shape == cvt_img.shape
  188. def test_adjust_gamma_pipeline_py():
  189. """
  190. Test AdjustGamma python Op Pipeline
  191. """
  192. # First dataset
  193. transforms1 = [F.Decode(), F.Resize([64, 64]), F.ToTensor()]
  194. transforms1 = mindspore.dataset.transforms.py_transforms.Compose(
  195. transforms1)
  196. ds1 = ds.TFRecordDataset(DATA_DIR_2,
  197. SCHEMA_DIR,
  198. columns_list=["image"],
  199. shuffle=False)
  200. ds1 = ds1.map(operations=transforms1, input_columns=["image"])
  201. # Second dataset
  202. transforms2 = [
  203. F.Decode(),
  204. F.Resize([64, 64]),
  205. F.AdjustGamma(1.0, 1.0),
  206. F.ToTensor()
  207. ]
  208. transform2 = mindspore.dataset.transforms.py_transforms.Compose(
  209. transforms2)
  210. ds2 = ds.TFRecordDataset(DATA_DIR_2,
  211. SCHEMA_DIR,
  212. columns_list=["image"],
  213. shuffle=False)
  214. ds2 = ds2.map(operations=transform2, input_columns=["image"])
  215. num_iter = 0
  216. for data1, data2 in zip(ds1.create_dict_iterator(num_epochs=1),
  217. ds2.create_dict_iterator(num_epochs=1)):
  218. num_iter += 1
  219. ori_img = data1["image"].asnumpy()
  220. cvt_img = data2["image"].asnumpy()
  221. assert_allclose(ori_img.flatten(),
  222. cvt_img.flatten(),
  223. rtol=1e-5,
  224. atol=0)
  225. assert ori_img.shape == cvt_img.shape
  226. def test_adjust_gamma_pipeline_py_gray():
  227. """
  228. Test AdjustGamma python Op Pipeline 1-channel
  229. """
  230. # First dataset
  231. transforms1 = [F.Decode(), F.Resize([64, 64]), F.Grayscale(), F.ToTensor()]
  232. transforms1 = mindspore.dataset.transforms.py_transforms.Compose(
  233. transforms1)
  234. ds1 = ds.TFRecordDataset(DATA_DIR_2,
  235. SCHEMA_DIR,
  236. columns_list=["image"],
  237. shuffle=False)
  238. ds1 = ds1.map(operations=transforms1, input_columns=["image"])
  239. # Second dataset
  240. transforms2 = [
  241. F.Decode(),
  242. F.Resize([64, 64]),
  243. F.Grayscale(),
  244. F.AdjustGamma(1.0, 1.0),
  245. F.ToTensor()
  246. ]
  247. transform2 = mindspore.dataset.transforms.py_transforms.Compose(
  248. transforms2)
  249. ds2 = ds.TFRecordDataset(DATA_DIR_2,
  250. SCHEMA_DIR,
  251. columns_list=["image"],
  252. shuffle=False)
  253. ds2 = ds2.map(operations=transform2, input_columns=["image"])
  254. num_iter = 0
  255. for data1, data2 in zip(ds1.create_dict_iterator(num_epochs=1),
  256. ds2.create_dict_iterator(num_epochs=1)):
  257. num_iter += 1
  258. ori_img = data1["image"].asnumpy()
  259. cvt_img = data2["image"].asnumpy()
  260. assert_allclose(ori_img.flatten(),
  261. cvt_img.flatten(),
  262. rtol=1e-5,
  263. atol=0)
  264. if __name__ == "__main__":
  265. test_adjust_gamma_c_eager()
  266. test_adjust_gamma_py_eager()
  267. test_adjust_gamma_c_eager_gray()
  268. test_adjust_gamma_py_eager_gray()
  269. test_adjust_gamma_invalid_gamma_param_c()
  270. test_adjust_gamma_invalid_gamma_param_py()
  271. test_adjust_gamma_invalid_gain_param_c()
  272. test_adjust_gamma_invalid_gain_param_py()
  273. test_adjust_gamma_pipeline_c()
  274. test_adjust_gamma_pipeline_py()
  275. test_adjust_gamma_pipeline_py_gray()