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

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