det_transforms.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. try:
  15. from collections.abc import Sequence
  16. except Exception:
  17. from collections import Sequence
  18. import random
  19. import os.path as osp
  20. import numpy as np
  21. import cv2
  22. from PIL import Image, ImageEnhance
  23. from .ops import *
  24. class DetTransform:
  25. """检测数据处理基类
  26. """
  27. def __init__(self):
  28. pass
  29. class Compose(DetTransform):
  30. """根据数据预处理/增强列表对输入数据进行操作。
  31. 所有操作的输入图像流形状均是[H, W, C],其中H为图像高,W为图像宽,C为图像通道数。
  32. Args:
  33. transforms (list): 数据预处理/增强列表。
  34. Raises:
  35. TypeError: 形参数据类型不满足需求。
  36. ValueError: 数据长度不匹配。
  37. """
  38. def __init__(self, transforms):
  39. if not isinstance(transforms, list):
  40. raise TypeError('The transforms must be a list!')
  41. if len(transforms) < 1:
  42. raise ValueError('The length of transforms ' + \
  43. 'must be equal or larger than 1!')
  44. self.transforms = transforms
  45. self.use_mixup = False
  46. for t in self.transforms:
  47. if type(t).__name__ == 'MixupImage':
  48. self.use_mixup = True
  49. def __call__(self, im, im_info=None, label_info=None):
  50. """
  51. Args:
  52. im (str/np.ndarray): 图像路径/图像np.ndarray数据。
  53. im_info (dict): 存储与图像相关的信息,dict中的字段如下:
  54. - im_id (np.ndarray): 图像序列号,形状为(1,)。
  55. - image_shape (np.ndarray): 图像原始大小,形状为(2,),
  56. image_shape[0]为高,image_shape[1]为宽。
  57. - mixup (list): list为[im, im_info, label_info],分别对应
  58. 与当前图像进行mixup的图像np.ndarray数据、图像相关信息、标注框相关信息;
  59. 注意,当前epoch若无需进行mixup,则无该字段。
  60. label_info (dict): 存储与标注框相关的信息,dict中的字段如下:
  61. - gt_bbox (np.ndarray): 真实标注框坐标[x1, y1, x2, y2],形状为(n, 4),
  62. 其中n代表真实标注框的个数。
  63. - gt_class (np.ndarray): 每个真实标注框对应的类别序号,形状为(n, 1),
  64. 其中n代表真实标注框的个数。
  65. - gt_score (np.ndarray): 每个真实标注框对应的混合得分,形状为(n, 1),
  66. 其中n代表真实标注框的个数。
  67. - gt_poly (list): 每个真实标注框内的多边形分割区域,每个分割区域由点的x、y坐标组成,
  68. 长度为n,其中n代表真实标注框的个数。
  69. - is_crowd (np.ndarray): 每个真实标注框中是否是一组对象,形状为(n, 1),
  70. 其中n代表真实标注框的个数。
  71. - difficult (np.ndarray): 每个真实标注框中的对象是否为难识别对象,形状为(n, 1),
  72. 其中n代表真实标注框的个数。
  73. Returns:
  74. tuple: 根据网络所需字段所组成的tuple;
  75. 字段由transforms中的最后一个数据预处理操作决定。
  76. """
  77. def decode_image(im_file, im_info, label_info):
  78. if im_info is None:
  79. im_info = dict()
  80. if isinstance(im_file, np.ndarray):
  81. if len(im_file.shape) != 3:
  82. raise Exception(
  83. "im should be 3-dimensions, but now is {}-dimensions".
  84. format(len(im_file.shape)))
  85. im = im_file
  86. else:
  87. try:
  88. im = cv2.imread(im_file).astype('float32')
  89. except:
  90. raise TypeError('Can\'t read The image file {}!'.format(
  91. im_file))
  92. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  93. # make default im_info with [h, w, 1]
  94. im_info['im_resize_info'] = np.array(
  95. [im.shape[0], im.shape[1], 1.], dtype=np.float32)
  96. im_info['image_shape'] = np.array([im.shape[0],
  97. im.shape[1]]).astype('int32')
  98. if not self.use_mixup:
  99. if 'mixup' in im_info:
  100. del im_info['mixup']
  101. # decode mixup image
  102. if 'mixup' in im_info:
  103. im_info['mixup'] = \
  104. decode_image(im_info['mixup'][0],
  105. im_info['mixup'][1],
  106. im_info['mixup'][2])
  107. if label_info is None:
  108. return (im, im_info)
  109. else:
  110. return (im, im_info, label_info)
  111. outputs = decode_image(im, im_info, label_info)
  112. im = outputs[0]
  113. im_info = outputs[1]
  114. if len(outputs) == 3:
  115. label_info = outputs[2]
  116. for op in self.transforms:
  117. if im is None:
  118. return None
  119. outputs = op(im, im_info, label_info)
  120. im = outputs[0]
  121. return outputs
  122. def add_augmenters(self, augmenters):
  123. if not isinstance(augmenters, list):
  124. raise Exception(
  125. "augmenters should be list type in func add_augmenters()")
  126. transform_names = [type(x).__name__ for x in self.transforms]
  127. for aug in augmenters:
  128. if type(aug).__name__ in transform_names:
  129. print(
  130. "{} is already in ComposedTransforms, need to remove it from add_augmenters().".
  131. format(type(aug).__name__))
  132. self.transforms = augmenters + self.transforms
  133. class ResizeByShort(DetTransform):
  134. """根据图像的短边调整图像大小(resize)。
  135. 1. 获取图像的长边和短边长度。
  136. 2. 根据短边与short_size的比例,计算长边的目标长度,
  137. 此时高、宽的resize比例为short_size/原图短边长度。
  138. 3. 如果max_size>0,调整resize比例:
  139. 如果长边的目标长度>max_size,则高、宽的resize比例为max_size/原图长边长度。
  140. 4. 根据调整大小的比例对图像进行resize。
  141. Args:
  142. target_size (int): 短边目标长度。默认为800。
  143. max_size (int): 长边目标长度的最大限制。默认为1333。
  144. Raises:
  145. TypeError: 形参数据类型不满足需求。
  146. """
  147. def __init__(self, short_size=800, max_size=1333):
  148. self.max_size = int(max_size)
  149. if not isinstance(short_size, int):
  150. raise TypeError(
  151. "Type of short_size is invalid. Must be Integer, now is {}".
  152. format(type(short_size)))
  153. self.short_size = short_size
  154. if not (isinstance(self.max_size, int)):
  155. raise TypeError("max_size: input type is invalid.")
  156. def __call__(self, im, im_info=None, label_info=None):
  157. """
  158. Args:
  159. im (numnp.ndarraypy): 图像np.ndarray数据。
  160. im_info (dict, 可选): 存储与图像相关的信息。
  161. label_info (dict, 可选): 存储与标注框相关的信息。
  162. Returns:
  163. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  164. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  165. 存储与标注框相关信息的字典。
  166. 其中,im_info更新字段为:
  167. - im_resize_info (np.ndarray): resize后的图像高、resize后的图像宽、resize后的图像相对原始图的缩放比例
  168. 三者组成的np.ndarray,形状为(3,)。
  169. Raises:
  170. TypeError: 形参数据类型不满足需求。
  171. ValueError: 数据长度不匹配。
  172. """
  173. if im_info is None:
  174. im_info = dict()
  175. if not isinstance(im, np.ndarray):
  176. raise TypeError("ResizeByShort: image type is not numpy.")
  177. if len(im.shape) != 3:
  178. raise ValueError('ResizeByShort: image is not 3-dimensional.')
  179. im_short_size = min(im.shape[0], im.shape[1])
  180. im_long_size = max(im.shape[0], im.shape[1])
  181. scale = float(self.short_size) / im_short_size
  182. if self.max_size > 0 and np.round(scale *
  183. im_long_size) > self.max_size:
  184. scale = float(self.max_size) / float(im_long_size)
  185. resized_width = int(round(im.shape[1] * scale))
  186. resized_height = int(round(im.shape[0] * scale))
  187. im_resize_info = [resized_height, resized_width, scale]
  188. im = cv2.resize(
  189. im, (resized_width, resized_height),
  190. interpolation=cv2.INTER_LINEAR)
  191. im_info['im_resize_info'] = np.array(im_resize_info).astype(np.float32)
  192. if label_info is None:
  193. return (im, im_info)
  194. else:
  195. return (im, im_info, label_info)
  196. class Padding(DetTransform):
  197. """1.将图像的长和宽padding至coarsest_stride的倍数。如输入图像为[300, 640],
  198. `coarest_stride`为32,则由于300不为32的倍数,因此在图像最右和最下使用0值
  199. 进行padding,最终输出图像为[320, 640]。
  200. 2.或者,将图像的长和宽padding到target_size指定的shape,如输入的图像为[300,640],
  201. a. `target_size` = 960,在图像最右和最下使用0值进行padding,最终输出
  202. 图像为[960, 960]。
  203. b. `target_size` = [640, 960],在图像最右和最下使用0值进行padding,最终
  204. 输出图像为[640, 960]。
  205. 1. 如果coarsest_stride为1,target_size为None则直接返回。
  206. 2. 获取图像的高H、宽W。
  207. 3. 计算填充后图像的高H_new、宽W_new。
  208. 4. 构建大小为(H_new, W_new, 3)像素值为0的np.ndarray,
  209. 并将原图的np.ndarray粘贴于左上角。
  210. Args:
  211. coarsest_stride (int): 填充后的图像长、宽为该参数的倍数,默认为1。
  212. target_size (int|list|tuple): 填充后的图像长、宽,默认为None,coarset_stride优先级更高。
  213. Raises:
  214. TypeError: 形参`target_size`数据类型不满足需求。
  215. ValueError: 形参`target_size`为(list|tuple)时,长度不满足需求。
  216. """
  217. def __init__(self, coarsest_stride=1, target_size=None):
  218. self.coarsest_stride = coarsest_stride
  219. if target_size is not None:
  220. if not isinstance(target_size, int):
  221. if not isinstance(target_size, tuple) and not isinstance(
  222. target_size, list):
  223. raise TypeError(
  224. "Padding: Type of target_size must in (int|list|tuple)."
  225. )
  226. elif len(target_size) != 2:
  227. raise ValueError(
  228. "Padding: Length of target_size must equal 2.")
  229. self.target_size = target_size
  230. def __call__(self, im, im_info=None, label_info=None):
  231. """
  232. Args:
  233. im (numnp.ndarraypy): 图像np.ndarray数据。
  234. im_info (dict, 可选): 存储与图像相关的信息。
  235. label_info (dict, 可选): 存储与标注框相关的信息。
  236. Returns:
  237. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  238. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  239. 存储与标注框相关信息的字典。
  240. Raises:
  241. TypeError: 形参数据类型不满足需求。
  242. ValueError: 数据长度不匹配。
  243. ValueError: coarsest_stride,target_size需有且只有一个被指定。
  244. ValueError: target_size小于原图的大小。
  245. """
  246. if im_info is None:
  247. im_info = dict()
  248. if not isinstance(im, np.ndarray):
  249. raise TypeError("Padding: image type is not numpy.")
  250. if len(im.shape) != 3:
  251. raise ValueError('Padding: image is not 3-dimensional.')
  252. im_h, im_w, im_c = im.shape[:]
  253. if isinstance(self.target_size, int):
  254. padding_im_h = self.target_size
  255. padding_im_w = self.target_size
  256. elif isinstance(self.target_size, list) or isinstance(self.target_size,
  257. tuple):
  258. padding_im_w = self.target_size[0]
  259. padding_im_h = self.target_size[1]
  260. elif self.coarsest_stride > 0:
  261. padding_im_h = int(
  262. np.ceil(im_h / self.coarsest_stride) * self.coarsest_stride)
  263. padding_im_w = int(
  264. np.ceil(im_w / self.coarsest_stride) * self.coarsest_stride)
  265. else:
  266. raise ValueError(
  267. "coarsest_stridei(>1) or target_size(list|int) need setting in Padding transform"
  268. )
  269. pad_height = padding_im_h - im_h
  270. pad_width = padding_im_w - im_w
  271. if pad_height < 0 or pad_width < 0:
  272. raise ValueError(
  273. 'the size of image should be less than target_size, but the size of image ({}, {}), is larger than target_size ({}, {})'
  274. .format(im_w, im_h, padding_im_w, padding_im_h))
  275. padding_im = np.zeros(
  276. (padding_im_h, padding_im_w, im_c), dtype=np.float32)
  277. padding_im[:im_h, :im_w, :] = im
  278. if label_info is None:
  279. return (padding_im, im_info)
  280. else:
  281. return (padding_im, im_info, label_info)
  282. class Resize(DetTransform):
  283. """调整图像大小(resize)。
  284. - 当目标大小(target_size)类型为int时,根据插值方式,
  285. 将图像resize为[target_size, target_size]。
  286. - 当目标大小(target_size)类型为list或tuple时,根据插值方式,
  287. 将图像resize为target_size。
  288. 注意:当插值方式为“RANDOM”时,则随机选取一种插值方式进行resize。
  289. Args:
  290. target_size (int/list/tuple): 短边目标长度。默认为608。
  291. interp (str): resize的插值方式,与opencv的插值方式对应,取值范围为
  292. ['NEAREST', 'LINEAR', 'CUBIC', 'AREA', 'LANCZOS4', 'RANDOM']。默认为"LINEAR"。
  293. Raises:
  294. TypeError: 形参数据类型不满足需求。
  295. ValueError: 插值方式不在['NEAREST', 'LINEAR', 'CUBIC',
  296. 'AREA', 'LANCZOS4', 'RANDOM']中。
  297. """
  298. # The interpolation mode
  299. interp_dict = {
  300. 'NEAREST': cv2.INTER_NEAREST,
  301. 'LINEAR': cv2.INTER_LINEAR,
  302. 'CUBIC': cv2.INTER_CUBIC,
  303. 'AREA': cv2.INTER_AREA,
  304. 'LANCZOS4': cv2.INTER_LANCZOS4
  305. }
  306. def __init__(self, target_size=608, interp='LINEAR'):
  307. self.interp = interp
  308. if not (interp == "RANDOM" or interp in self.interp_dict):
  309. raise ValueError("interp should be one of {}".format(
  310. self.interp_dict.keys()))
  311. if isinstance(target_size, list) or isinstance(target_size, tuple):
  312. if len(target_size) != 2:
  313. raise TypeError(
  314. 'when target is list or tuple, it should include 2 elements, but it is {}'
  315. .format(target_size))
  316. elif not isinstance(target_size, int):
  317. raise TypeError(
  318. "Type of target_size is invalid. Must be Integer or List or tuple, now is {}"
  319. .format(type(target_size)))
  320. self.target_size = target_size
  321. def __call__(self, im, im_info=None, label_info=None):
  322. """
  323. Args:
  324. im (np.ndarray): 图像np.ndarray数据。
  325. im_info (dict, 可选): 存储与图像相关的信息。
  326. label_info (dict, 可选): 存储与标注框相关的信息。
  327. Returns:
  328. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  329. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  330. 存储与标注框相关信息的字典。
  331. Raises:
  332. TypeError: 形参数据类型不满足需求。
  333. ValueError: 数据长度不匹配。
  334. """
  335. if im_info is None:
  336. im_info = dict()
  337. if not isinstance(im, np.ndarray):
  338. raise TypeError("Resize: image type is not numpy.")
  339. if len(im.shape) != 3:
  340. raise ValueError('Resize: image is not 3-dimensional.')
  341. if self.interp == "RANDOM":
  342. interp = random.choice(list(self.interp_dict.keys()))
  343. else:
  344. interp = self.interp
  345. im = resize(im, self.target_size, self.interp_dict[interp])
  346. if label_info is None:
  347. return (im, im_info)
  348. else:
  349. return (im, im_info, label_info)
  350. class Normalize(DetTransform):
  351. """对图像进行标准化。
  352. 1. 归一化图像到到区间[0.0, 1.0]。
  353. 2. 对图像进行减均值除以标准差操作。
  354. Args:
  355. mean (list): 图像数据集的均值。默认为[0.485, 0.456, 0.406]。
  356. std (list): 图像数据集的标准差。默认为[0.229, 0.224, 0.225]。
  357. Raises:
  358. TypeError: 形参数据类型不满足需求。
  359. """
  360. def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
  361. self.mean = mean
  362. self.std = std
  363. if not (isinstance(self.mean, list) and isinstance(self.std, list)):
  364. raise TypeError("NormalizeImage: input type is invalid.")
  365. from functools import reduce
  366. if reduce(lambda x, y: x * y, self.std) == 0:
  367. raise TypeError('NormalizeImage: std is invalid!')
  368. def __call__(self, im, im_info=None, label_info=None):
  369. """
  370. Args:
  371. im (numnp.ndarraypy): 图像np.ndarray数据。
  372. im_info (dict, 可选): 存储与图像相关的信息。
  373. label_info (dict, 可选): 存储与标注框相关的信息。
  374. Returns:
  375. tuple: 当label_info为空时,返回的tuple为(im, im_info),分别对应图像np.ndarray数据、存储与图像相关信息的字典;
  376. 当label_info不为空时,返回的tuple为(im, im_info, label_info),分别对应图像np.ndarray数据、
  377. 存储与标注框相关信息的字典。
  378. """
  379. mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
  380. std = np.array(self.std)[np.newaxis, np.newaxis, :]
  381. im = normalize(im, mean, std)
  382. if label_info is None:
  383. return (im, im_info)
  384. else:
  385. return (im, im_info, label_info)
  386. class ArrangeYOLOv3(DetTransform):
  387. """获取YOLOv3模型训练/验证/预测所需信息。
  388. Args:
  389. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  390. Raises:
  391. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  392. """
  393. def __init__(self, mode=None):
  394. if mode not in ['train', 'eval', 'test', 'quant']:
  395. raise ValueError(
  396. "mode must be in ['train', 'eval', 'test', 'quant']!")
  397. self.mode = mode
  398. def __call__(self, im, im_info=None, label_info=None):
  399. """
  400. Args:
  401. im (np.ndarray): 图像np.ndarray数据。
  402. im_info (dict, 可选): 存储与图像相关的信息。
  403. label_info (dict, 可选): 存储与标注框相关的信息。
  404. Returns:
  405. tuple: 当mode为'train'时,返回(im, gt_bbox, gt_class, gt_score, im_shape),分别对应
  406. 图像np.ndarray数据、真实标注框、真实标注框对应的类别、真实标注框混合得分、图像大小信息;
  407. 当mode为'eval'时,返回(im, im_shape, im_id, gt_bbox, gt_class, difficult),
  408. 分别对应图像np.ndarray数据、图像大小信息、图像id、真实标注框、真实标注框对应的类别、
  409. 真实标注框是否为难识别对象;当mode为'test'或'quant'时,返回(im, im_shape),
  410. 分别对应图像np.ndarray数据、图像大小信息。
  411. Raises:
  412. TypeError: 形参数据类型不满足需求。
  413. ValueError: 数据长度不匹配。
  414. """
  415. im = permute(im, False)
  416. if self.mode == 'train':
  417. pass
  418. elif self.mode == 'eval':
  419. pass
  420. else:
  421. if im_info is None:
  422. raise TypeError('Cannot do ArrangeYolov3! ' +
  423. 'Becasuse the im_info can not be None!')
  424. im_shape = im_info['image_shape']
  425. outputs = (im, im_shape)
  426. return outputs
  427. class ComposedYOLOv3Transforms(Compose):
  428. """YOLOv3模型的图像预处理流程,具体如下,
  429. 训练阶段:
  430. 1. 在前mixup_epoch轮迭代中,使用MixupImage策略,见https://paddlex.readthedocs.io/zh_CN/latest/apis/transforms/det_transforms.html#mixupimage
  431. 2. 对图像进行随机扰动,包括亮度,对比度,饱和度和色调
  432. 3. 随机扩充图像,见https://paddlex.readthedocs.io/zh_CN/latest/apis/transforms/det_transforms.html#randomexpand
  433. 4. 随机裁剪图像
  434. 5. 将4步骤的输出图像Resize成shape参数的大小
  435. 6. 随机0.5的概率水平翻转图像
  436. 7. 图像归一化
  437. 验证/预测阶段:
  438. 1. 将图像Resize成shape参数大小
  439. 2. 图像归一化
  440. Args:
  441. mode(str): 图像处理流程所处阶段,训练/验证/预测,分别对应'train', 'eval', 'test'
  442. shape(list): 输入模型中图像的大小,输入模型的图像会被Resize成此大小
  443. mixup_epoch(int): 模型训练过程中,前mixup_epoch会使用mixup策略
  444. mean(list): 图像均值
  445. std(list): 图像方差
  446. """
  447. def __init__(self,
  448. mode,
  449. shape=[608, 608],
  450. mixup_epoch=250,
  451. mean=[0.485, 0.456, 0.406],
  452. std=[0.229, 0.224, 0.225]):
  453. width = shape
  454. if isinstance(shape, list):
  455. if shape[0] != shape[1]:
  456. raise Exception(
  457. "In YOLOv3 model, width and height should be equal")
  458. width = shape[0]
  459. if width % 32 != 0:
  460. raise Exception(
  461. "In YOLOv3 model, width and height should be multiple of 32, e.g 224、256、320...."
  462. )
  463. if mode == 'train':
  464. # 训练时的transforms,包含数据增强
  465. pass
  466. else:
  467. # 验证/预测时的transforms
  468. transforms = [
  469. Resize(
  470. target_size=width, interp='CUBIC'), Normalize(
  471. mean=mean, std=std)
  472. ]
  473. super(ComposedYOLOv3Transforms, self).__init__(transforms)