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_autocontrast.py 14 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. # Copyright 2020 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 AutoContrast op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset.engine as de
  20. import mindspore.dataset.transforms.vision.py_transforms as F
  21. import mindspore.dataset.transforms.vision.c_transforms as C
  22. from mindspore import log as logger
  23. from util import visualize_list, diff_mse, save_and_check_md5
  24. DATA_DIR = "../data/dataset/testImageNetData/train/"
  25. GENERATE_GOLDEN = False
  26. def test_auto_contrast_py(plot=False):
  27. """
  28. Test AutoContrast
  29. """
  30. logger.info("Test AutoContrast Python Op")
  31. # Original Images
  32. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  33. transforms_original = F.ComposeOp([F.Decode(),
  34. F.Resize((224, 224)),
  35. F.ToTensor()])
  36. ds_original = ds.map(input_columns="image",
  37. operations=transforms_original())
  38. ds_original = ds_original.batch(512)
  39. for idx, (image, _) in enumerate(ds_original):
  40. if idx == 0:
  41. images_original = np.transpose(image, (0, 2, 3, 1))
  42. else:
  43. images_original = np.append(images_original,
  44. np.transpose(image, (0, 2, 3, 1)),
  45. axis=0)
  46. # AutoContrast Images
  47. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  48. transforms_auto_contrast = F.ComposeOp([F.Decode(),
  49. F.Resize((224, 224)),
  50. F.AutoContrast(cutoff=10.0, ignore=[10, 20]),
  51. F.ToTensor()])
  52. ds_auto_contrast = ds.map(input_columns="image",
  53. operations=transforms_auto_contrast())
  54. ds_auto_contrast = ds_auto_contrast.batch(512)
  55. for idx, (image, _) in enumerate(ds_auto_contrast):
  56. if idx == 0:
  57. images_auto_contrast = np.transpose(image, (0, 2, 3, 1))
  58. else:
  59. images_auto_contrast = np.append(images_auto_contrast,
  60. np.transpose(image, (0, 2, 3, 1)),
  61. axis=0)
  62. num_samples = images_original.shape[0]
  63. mse = np.zeros(num_samples)
  64. for i in range(num_samples):
  65. mse[i] = diff_mse(images_auto_contrast[i], images_original[i])
  66. logger.info("MSE= {}".format(str(np.mean(mse))))
  67. # Compare with expected md5 from images
  68. filename = "autcontrast_01_result_py.npz"
  69. save_and_check_md5(ds_auto_contrast, filename, generate_golden=GENERATE_GOLDEN)
  70. if plot:
  71. visualize_list(images_original, images_auto_contrast)
  72. def test_auto_contrast_c(plot=False):
  73. """
  74. Test AutoContrast C Op
  75. """
  76. logger.info("Test AutoContrast C Op")
  77. # AutoContrast Images
  78. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  79. ds = ds.map(input_columns=["image"],
  80. operations=[C.Decode(),
  81. C.Resize((224, 224))])
  82. python_op = F.AutoContrast(cutoff=10.0, ignore=[10, 20])
  83. c_op = C.AutoContrast(cutoff=10.0, ignore=[10, 20])
  84. transforms_op = F.ComposeOp([lambda img: F.ToPIL()(img.astype(np.uint8)),
  85. python_op,
  86. np.array])()
  87. ds_auto_contrast_py = ds.map(input_columns="image",
  88. operations=transforms_op)
  89. ds_auto_contrast_py = ds_auto_contrast_py.batch(512)
  90. for idx, (image, _) in enumerate(ds_auto_contrast_py):
  91. if idx == 0:
  92. images_auto_contrast_py = image
  93. else:
  94. images_auto_contrast_py = np.append(images_auto_contrast_py,
  95. image,
  96. axis=0)
  97. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  98. ds = ds.map(input_columns=["image"],
  99. operations=[C.Decode(),
  100. C.Resize((224, 224))])
  101. ds_auto_contrast_c = ds.map(input_columns="image",
  102. operations=c_op)
  103. ds_auto_contrast_c = ds_auto_contrast_c.batch(512)
  104. for idx, (image, _) in enumerate(ds_auto_contrast_c):
  105. if idx == 0:
  106. images_auto_contrast_c = image
  107. else:
  108. images_auto_contrast_c = np.append(images_auto_contrast_c,
  109. image,
  110. axis=0)
  111. num_samples = images_auto_contrast_c.shape[0]
  112. mse = np.zeros(num_samples)
  113. for i in range(num_samples):
  114. mse[i] = diff_mse(images_auto_contrast_c[i], images_auto_contrast_py[i])
  115. logger.info("MSE= {}".format(str(np.mean(mse))))
  116. np.testing.assert_equal(np.mean(mse), 0.0)
  117. # Compare with expected md5 from images
  118. filename = "autcontrast_01_result_c.npz"
  119. save_and_check_md5(ds_auto_contrast_c, filename, generate_golden=GENERATE_GOLDEN)
  120. if plot:
  121. visualize_list(images_auto_contrast_c, images_auto_contrast_py, visualize_mode=2)
  122. def test_auto_contrast_one_channel_c(plot=False):
  123. """
  124. Test AutoContrast C op with one channel
  125. """
  126. logger.info("Test AutoContrast C Op With One Channel Images")
  127. # AutoContrast Images
  128. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  129. ds = ds.map(input_columns=["image"],
  130. operations=[C.Decode(),
  131. C.Resize((224, 224))])
  132. python_op = F.AutoContrast()
  133. c_op = C.AutoContrast()
  134. # not using F.ToTensor() since it converts to floats
  135. transforms_op = F.ComposeOp([lambda img: (np.array(img)[:, :, 0]).astype(np.uint8),
  136. F.ToPIL(),
  137. python_op,
  138. np.array])()
  139. ds_auto_contrast_py = ds.map(input_columns="image",
  140. operations=transforms_op)
  141. ds_auto_contrast_py = ds_auto_contrast_py.batch(512)
  142. for idx, (image, _) in enumerate(ds_auto_contrast_py):
  143. if idx == 0:
  144. images_auto_contrast_py = image
  145. else:
  146. images_auto_contrast_py = np.append(images_auto_contrast_py,
  147. image,
  148. axis=0)
  149. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  150. ds = ds.map(input_columns=["image"],
  151. operations=[C.Decode(),
  152. C.Resize((224, 224)),
  153. lambda img: np.array(img[:, :, 0])])
  154. ds_auto_contrast_c = ds.map(input_columns="image",
  155. operations=c_op)
  156. ds_auto_contrast_c = ds_auto_contrast_c.batch(512)
  157. for idx, (image, _) in enumerate(ds_auto_contrast_c):
  158. if idx == 0:
  159. images_auto_contrast_c = image
  160. else:
  161. images_auto_contrast_c = np.append(images_auto_contrast_c,
  162. image,
  163. axis=0)
  164. num_samples = images_auto_contrast_c.shape[0]
  165. mse = np.zeros(num_samples)
  166. for i in range(num_samples):
  167. mse[i] = diff_mse(images_auto_contrast_c[i], images_auto_contrast_py[i])
  168. logger.info("MSE= {}".format(str(np.mean(mse))))
  169. np.testing.assert_equal(np.mean(mse), 0.0)
  170. if plot:
  171. visualize_list(images_auto_contrast_c, images_auto_contrast_py, visualize_mode=2)
  172. def test_auto_contrast_invalid_ignore_param_c():
  173. """
  174. Test AutoContrast C Op with invalid ignore parameter
  175. """
  176. logger.info("Test AutoContrast C Op with invalid ignore parameter")
  177. try:
  178. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  179. ds = ds.map(input_columns=["image"],
  180. operations=[C.Decode(),
  181. C.Resize((224, 224)),
  182. lambda img: np.array(img[:, :, 0])])
  183. # invalid ignore
  184. ds = ds.map(input_columns="image",
  185. operations=C.AutoContrast(ignore=255.5))
  186. except TypeError as error:
  187. logger.info("Got an exception in DE: {}".format(str(error)))
  188. assert "Argument ignore with value 255.5 is not of type" in str(error)
  189. try:
  190. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  191. ds = ds.map(input_columns=["image"],
  192. operations=[C.Decode(),
  193. C.Resize((224, 224)),
  194. lambda img: np.array(img[:, :, 0])])
  195. # invalid ignore
  196. ds = ds.map(input_columns="image",
  197. operations=C.AutoContrast(ignore=(10, 100)))
  198. except TypeError as error:
  199. logger.info("Got an exception in DE: {}".format(str(error)))
  200. assert "Argument ignore with value (10,100) is not of type" in str(error)
  201. def test_auto_contrast_invalid_cutoff_param_c():
  202. """
  203. Test AutoContrast C Op with invalid cutoff parameter
  204. """
  205. logger.info("Test AutoContrast C Op with invalid cutoff parameter")
  206. try:
  207. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  208. ds = ds.map(input_columns=["image"],
  209. operations=[C.Decode(),
  210. C.Resize((224, 224)),
  211. lambda img: np.array(img[:, :, 0])])
  212. # invalid ignore
  213. ds = ds.map(input_columns="image",
  214. operations=C.AutoContrast(cutoff=-10.0))
  215. except ValueError as error:
  216. logger.info("Got an exception in DE: {}".format(str(error)))
  217. assert "Input cutoff is not within the required interval of (0 to 100)." in str(error)
  218. try:
  219. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  220. ds = ds.map(input_columns=["image"],
  221. operations=[C.Decode(),
  222. C.Resize((224, 224)),
  223. lambda img: np.array(img[:, :, 0])])
  224. # invalid ignore
  225. ds = ds.map(input_columns="image",
  226. operations=C.AutoContrast(cutoff=120.0))
  227. except ValueError as error:
  228. logger.info("Got an exception in DE: {}".format(str(error)))
  229. assert "Input cutoff is not within the required interval of (0 to 100)." in str(error)
  230. def test_auto_contrast_invalid_ignore_param_py():
  231. """
  232. Test AutoContrast python Op with invalid ignore parameter
  233. """
  234. logger.info("Test AutoContrast python Op with invalid ignore parameter")
  235. try:
  236. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  237. ds = ds.map(input_columns=["image"],
  238. operations=[F.ComposeOp([F.Decode(),
  239. F.Resize((224, 224)),
  240. F.AutoContrast(ignore=255.5),
  241. F.ToTensor()])])
  242. except TypeError as error:
  243. logger.info("Got an exception in DE: {}".format(str(error)))
  244. assert "Argument ignore with value 255.5 is not of type" in str(error)
  245. try:
  246. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  247. ds = ds.map(input_columns=["image"],
  248. operations=[F.ComposeOp([F.Decode(),
  249. F.Resize((224, 224)),
  250. F.AutoContrast(ignore=(10, 100)),
  251. F.ToTensor()])])
  252. except TypeError as error:
  253. logger.info("Got an exception in DE: {}".format(str(error)))
  254. assert "Argument ignore with value (10,100) is not of type" in str(error)
  255. def test_auto_contrast_invalid_cutoff_param_py():
  256. """
  257. Test AutoContrast python Op with invalid cutoff parameter
  258. """
  259. logger.info("Test AutoContrast python Op with invalid cutoff parameter")
  260. try:
  261. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  262. ds = ds.map(input_columns=["image"],
  263. operations=[F.ComposeOp([F.Decode(),
  264. F.Resize((224, 224)),
  265. F.AutoContrast(cutoff=-10.0),
  266. F.ToTensor()])])
  267. except ValueError as error:
  268. logger.info("Got an exception in DE: {}".format(str(error)))
  269. assert "Input cutoff is not within the required interval of (0 to 100)." in str(error)
  270. try:
  271. ds = de.ImageFolderDatasetV2(dataset_dir=DATA_DIR, shuffle=False)
  272. ds = ds.map(input_columns=["image"],
  273. operations=[F.ComposeOp([F.Decode(),
  274. F.Resize((224, 224)),
  275. F.AutoContrast(cutoff=120.0),
  276. F.ToTensor()])])
  277. except ValueError as error:
  278. logger.info("Got an exception in DE: {}".format(str(error)))
  279. assert "Input cutoff is not within the required interval of (0 to 100)." in str(error)
  280. if __name__ == "__main__":
  281. test_auto_contrast_py(plot=True)
  282. test_auto_contrast_c(plot=True)
  283. test_auto_contrast_one_channel_c(plot=True)
  284. test_auto_contrast_invalid_ignore_param_c()
  285. test_auto_contrast_invalid_ignore_param_py()
  286. test_auto_contrast_invalid_cutoff_param_c()
  287. test_auto_contrast_invalid_cutoff_param_py()