det_transforms.py 23 KB

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