common.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. import math
  15. from pathlib import Path
  16. from copy import deepcopy
  17. import numpy as np
  18. import cv2
  19. from .....utils.cache import CACHE_DIR, temp_file_manager
  20. from ....utils.io import ImageReader, ImageWriter, PDFReader
  21. from ...base import BaseComponent
  22. from ..read_data import _BaseRead
  23. from . import funcs as F
  24. __all__ = [
  25. "ReadImage",
  26. "Flip",
  27. "Crop",
  28. "Resize",
  29. "ResizeByLong",
  30. "ResizeByShort",
  31. "Pad",
  32. "Normalize",
  33. "ToCHWImage",
  34. "PadStride",
  35. ]
  36. def _check_image_size(input_):
  37. """check image size"""
  38. if not (
  39. isinstance(input_, (list, tuple))
  40. and len(input_) == 2
  41. and isinstance(input_[0], int)
  42. and isinstance(input_[1], int)
  43. ):
  44. raise TypeError(f"{input_} cannot represent a valid image size.")
  45. class ReadImage(_BaseRead):
  46. """Load image from the file."""
  47. INPUT_KEYS = ["img"]
  48. OUTPUT_KEYS = ["img", "img_size", "ori_img", "ori_img_size"]
  49. DEAULT_INPUTS = {"img": "img"}
  50. DEAULT_OUTPUTS = {
  51. "img": "img",
  52. "input_path": "input_path",
  53. "img_size": "img_size",
  54. "ori_img": "ori_img",
  55. "ori_img_size": "ori_img_size",
  56. }
  57. _FLAGS_DICT = {
  58. "BGR": cv2.IMREAD_COLOR,
  59. "RGB": cv2.IMREAD_COLOR,
  60. "GRAY": cv2.IMREAD_GRAYSCALE,
  61. }
  62. SUFFIX = ["jpg", "png", "jpeg", "JPEG", "JPG", "bmp", "PDF", "pdf"]
  63. def __init__(self, batch_size=1, format="BGR"):
  64. """
  65. Initialize the instance.
  66. Args:
  67. format (str, optional): Target color format to convert the image to.
  68. Choices are 'BGR', 'RGB', and 'GRAY'. Default: 'BGR'.
  69. """
  70. super().__init__(batch_size)
  71. self.format = format
  72. flags = self._FLAGS_DICT[self.format]
  73. self._img_reader = ImageReader(backend="opencv", flags=flags)
  74. self._pdf_reader = PDFReader()
  75. self._writer = ImageWriter(backend="opencv")
  76. def apply(self, img):
  77. """apply"""
  78. if isinstance(img, np.ndarray):
  79. with temp_file_manager.temp_file_context(suffix=".png") as temp_file:
  80. img_path = Path(temp_file.name)
  81. self._writer.write(img_path, img)
  82. if self.format == "RGB":
  83. img = img[:, :, ::-1]
  84. yield [
  85. {
  86. "input_path": img_path,
  87. "img": img,
  88. "img_size": [img.shape[1], img.shape[0]],
  89. "ori_img": deepcopy(img),
  90. "ori_img_size": deepcopy([img.shape[1], img.shape[0]]),
  91. }
  92. ]
  93. elif isinstance(img, str):
  94. file_path = img
  95. file_path = self._download_from_url(file_path)
  96. file_list = self._get_files_list(file_path)
  97. batch = []
  98. for file_path in file_list:
  99. img = self._read(file_path)
  100. batch.extend(img)
  101. if len(batch) >= self.batch_size:
  102. yield batch
  103. batch = []
  104. if len(batch) > 0:
  105. yield batch
  106. else:
  107. raise TypeError(
  108. f"ReadImage only supports the following types:\n"
  109. f"1. str, indicating a image file path or a directory containing image files.\n"
  110. f"2. numpy.ndarray.\n"
  111. f"However, got type: {type(img).__name__}."
  112. )
  113. def _read(self, file_path):
  114. if str(file_path).lower().endswith(".pdf"):
  115. return self._read_pdf(file_path)
  116. else:
  117. return self._read_img(file_path)
  118. def _read_img(self, img_path):
  119. blob = self._img_reader.read(img_path)
  120. if blob is None:
  121. raise Exception("Image read Error")
  122. if self.format == "RGB":
  123. if blob.ndim != 3:
  124. raise RuntimeError("Array is not 3-dimensional.")
  125. # BGR to RGB
  126. blob = blob[..., ::-1]
  127. return [
  128. {
  129. "input_path": img_path,
  130. "img": blob,
  131. "img_size": [blob.shape[1], blob.shape[0]],
  132. "ori_img": deepcopy(blob),
  133. "ori_img_size": deepcopy([blob.shape[1], blob.shape[0]]),
  134. }
  135. ]
  136. def _read_pdf(self, pdf_path):
  137. img_list = self._pdf_reader.read(pdf_path)
  138. return [
  139. {
  140. "input_path": pdf_path,
  141. "img": img,
  142. "img_size": [img.shape[1], img.shape[0]],
  143. "ori_img": deepcopy(img),
  144. "ori_img_size": deepcopy([img.shape[1], img.shape[0]]),
  145. }
  146. for img in img_list
  147. ]
  148. class GetImageInfo(BaseComponent):
  149. """Get Image Info"""
  150. INPUT_KEYS = "img"
  151. OUTPUT_KEYS = "img_size"
  152. DEAULT_INPUTS = {"img": "img"}
  153. DEAULT_OUTPUTS = {"img_size": "img_size"}
  154. def __init__(self):
  155. super().__init__()
  156. def apply(self, img):
  157. """apply"""
  158. return {"img_size": [img.shape[1], img.shape[0]]}
  159. class Flip(BaseComponent):
  160. """Flip the image vertically or horizontally."""
  161. INPUT_KEYS = "img"
  162. OUTPUT_KEYS = "img"
  163. DEAULT_INPUTS = {"img": "img"}
  164. DEAULT_OUTPUTS = {"img": "img"}
  165. def __init__(self, mode="H"):
  166. """
  167. Initialize the instance.
  168. Args:
  169. mode (str, optional): 'H' for horizontal flipping and 'V' for vertical
  170. flipping. Default: 'H'.
  171. """
  172. super().__init__()
  173. if mode not in ("H", "V"):
  174. raise ValueError("`mode` should be 'H' or 'V'.")
  175. self.mode = mode
  176. def apply(self, img):
  177. """apply"""
  178. if self.mode == "H":
  179. img = F.flip_h(img)
  180. elif self.mode == "V":
  181. img = F.flip_v(img)
  182. return {"img": img}
  183. class Crop(BaseComponent):
  184. """Crop region from the image."""
  185. INPUT_KEYS = "img"
  186. OUTPUT_KEYS = ["img", "img_size"]
  187. DEAULT_INPUTS = {"img": "img"}
  188. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  189. def __init__(self, crop_size, mode="C"):
  190. """
  191. Initialize the instance.
  192. Args:
  193. crop_size (list|tuple|int): Width and height of the region to crop.
  194. mode (str, optional): 'C' for cropping the center part and 'TL' for
  195. cropping the top left part. Default: 'C'.
  196. """
  197. super().__init__()
  198. if isinstance(crop_size, int):
  199. crop_size = [crop_size, crop_size]
  200. _check_image_size(crop_size)
  201. self.crop_size = crop_size
  202. if mode not in ("C", "TL"):
  203. raise ValueError("Unsupported interpolation method")
  204. self.mode = mode
  205. def apply(self, img):
  206. """apply"""
  207. h, w = img.shape[:2]
  208. cw, ch = self.crop_size
  209. if self.mode == "C":
  210. x1 = max(0, (w - cw) // 2)
  211. y1 = max(0, (h - ch) // 2)
  212. elif self.mode == "TL":
  213. x1, y1 = 0, 0
  214. x2 = min(w, x1 + cw)
  215. y2 = min(h, y1 + ch)
  216. coords = (x1, y1, x2, y2)
  217. if coords == (0, 0, w, h):
  218. raise ValueError(
  219. f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch})."
  220. )
  221. img = F.slice(img, coords=coords)
  222. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  223. class _BaseResize(BaseComponent):
  224. _INTERP_DICT = {
  225. "NEAREST": cv2.INTER_NEAREST,
  226. "LINEAR": cv2.INTER_LINEAR,
  227. "CUBIC": cv2.INTER_CUBIC,
  228. "AREA": cv2.INTER_AREA,
  229. "LANCZOS4": cv2.INTER_LANCZOS4,
  230. }
  231. def __init__(self, size_divisor, interp):
  232. super().__init__()
  233. if size_divisor is not None:
  234. assert isinstance(
  235. size_divisor, int
  236. ), "`size_divisor` should be None or int."
  237. self.size_divisor = size_divisor
  238. try:
  239. interp = self._INTERP_DICT[interp]
  240. except KeyError:
  241. raise ValueError(
  242. "`interp` should be one of {}.".format(self._INTERP_DICT.keys())
  243. )
  244. self.interp = interp
  245. @staticmethod
  246. def _rescale_size(img_size, target_size):
  247. """rescale size"""
  248. scale = min(max(target_size) / max(img_size), min(target_size) / min(img_size))
  249. rescaled_size = [round(i * scale) for i in img_size]
  250. return rescaled_size, scale
  251. class Resize(_BaseResize):
  252. """Resize the image."""
  253. INPUT_KEYS = "img"
  254. OUTPUT_KEYS = ["img", "img_size", "scale_factors"]
  255. DEAULT_INPUTS = {"img": "img"}
  256. DEAULT_OUTPUTS = {
  257. "img": "img",
  258. "img_size": "img_size",
  259. "scale_factors": "scale_factors",
  260. }
  261. def __init__(
  262. self, target_size, keep_ratio=False, size_divisor=None, interp="LINEAR"
  263. ):
  264. """
  265. Initialize the instance.
  266. Args:
  267. target_size (list|tuple|int): Target width and height.
  268. keep_ratio (bool, optional): Whether to keep the aspect ratio of resized
  269. image. Default: False.
  270. size_divisor (int|None, optional): Divisor of resized image size.
  271. Default: None.
  272. interp (str, optional): Interpolation method. Choices are 'NEAREST',
  273. 'LINEAR', 'CUBIC', 'AREA', and 'LANCZOS4'. Default: 'LINEAR'.
  274. """
  275. super().__init__(size_divisor=size_divisor, interp=interp)
  276. if isinstance(target_size, int):
  277. target_size = [target_size, target_size]
  278. _check_image_size(target_size)
  279. self.target_size = target_size
  280. self.keep_ratio = keep_ratio
  281. def apply(self, img):
  282. """apply"""
  283. target_size = self.target_size
  284. original_size = img.shape[:2][::-1]
  285. if self.keep_ratio:
  286. h, w = img.shape[0:2]
  287. target_size, _ = self._rescale_size((w, h), self.target_size)
  288. if self.size_divisor:
  289. target_size = [
  290. math.ceil(i / self.size_divisor) * self.size_divisor
  291. for i in target_size
  292. ]
  293. img_scale_w, img_scale_h = [
  294. target_size[0] / original_size[0],
  295. target_size[1] / original_size[1],
  296. ]
  297. img = F.resize(img, target_size, interp=self.interp)
  298. return {
  299. "img": img,
  300. "img_size": [img.shape[1], img.shape[0]],
  301. "scale_factors": [img_scale_w, img_scale_h],
  302. }
  303. class ResizeByLong(_BaseResize):
  304. """
  305. Proportionally resize the image by specifying the target length of the
  306. longest side.
  307. """
  308. INPUT_KEYS = "img"
  309. OUTPUT_KEYS = ["img", "img_size"]
  310. DEAULT_INPUTS = {"img": "img"}
  311. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  312. def __init__(self, target_long_edge, size_divisor=None, interp="LINEAR"):
  313. """
  314. Initialize the instance.
  315. Args:
  316. target_long_edge (int): Target length of the longest side of image.
  317. size_divisor (int|None, optional): Divisor of resized image size.
  318. Default: None.
  319. interp (str, optional): Interpolation method. Choices are 'NEAREST',
  320. 'LINEAR', 'CUBIC', 'AREA', and 'LANCZOS4'. Default: 'LINEAR'.
  321. """
  322. super().__init__(size_divisor=size_divisor, interp=interp)
  323. self.target_long_edge = target_long_edge
  324. def apply(self, img):
  325. """apply"""
  326. h, w = img.shape[:2]
  327. scale = self.target_long_edge / max(h, w)
  328. h_resize = round(h * scale)
  329. w_resize = round(w * scale)
  330. if self.size_divisor is not None:
  331. h_resize = math.ceil(h_resize / self.size_divisor) * self.size_divisor
  332. w_resize = math.ceil(w_resize / self.size_divisor) * self.size_divisor
  333. img = F.resize(img, (w_resize, h_resize), interp=self.interp)
  334. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  335. class ResizeByShort(_BaseResize):
  336. """
  337. Proportionally resize the image by specifying the target length of the
  338. shortest side.
  339. """
  340. INPUT_KEYS = "img"
  341. OUTPUT_KEYS = ["img", "img_size"]
  342. DEAULT_INPUTS = {"img": "img"}
  343. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  344. def __init__(self, target_short_edge, size_divisor=None, interp="LINEAR"):
  345. """
  346. Initialize the instance.
  347. Args:
  348. target_short_edge (int): Target length of the shortest side of image.
  349. size_divisor (int|None, optional): Divisor of resized image size.
  350. Default: None.
  351. interp (str, optional): Interpolation method. Choices are 'NEAREST',
  352. 'LINEAR', 'CUBIC', 'AREA', and 'LANCZOS4'. Default: 'LINEAR'.
  353. """
  354. super().__init__(size_divisor=size_divisor, interp=interp)
  355. self.target_short_edge = target_short_edge
  356. def apply(self, img):
  357. """apply"""
  358. h, w = img.shape[:2]
  359. scale = self.target_short_edge / min(h, w)
  360. h_resize = round(h * scale)
  361. w_resize = round(w * scale)
  362. if self.size_divisor is not None:
  363. h_resize = math.ceil(h_resize / self.size_divisor) * self.size_divisor
  364. w_resize = math.ceil(w_resize / self.size_divisor) * self.size_divisor
  365. img = F.resize(img, (w_resize, h_resize), interp=self.interp)
  366. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  367. class Pad(BaseComponent):
  368. """Pad the image."""
  369. INPUT_KEYS = "img"
  370. OUTPUT_KEYS = ["img", "img_size"]
  371. DEAULT_INPUTS = {"img": "img"}
  372. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  373. def __init__(self, target_size, val=127.5):
  374. """
  375. Initialize the instance.
  376. Args:
  377. target_size (list|tuple|int): Target width and height of the image after
  378. padding.
  379. val (float, optional): Value to fill the padded area. Default: 127.5.
  380. """
  381. super().__init__()
  382. if isinstance(target_size, int):
  383. target_size = [target_size, target_size]
  384. _check_image_size(target_size)
  385. self.target_size = target_size
  386. self.val = val
  387. def apply(self, img):
  388. """apply"""
  389. h, w = img.shape[:2]
  390. tw, th = self.target_size
  391. ph = th - h
  392. pw = tw - w
  393. if ph < 0 or pw < 0:
  394. raise ValueError(
  395. f"Input image ({w}, {h}) smaller than the target size ({tw}, {th})."
  396. )
  397. else:
  398. img = F.pad(img, pad=(0, ph, 0, pw), val=self.val)
  399. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  400. class PadStride(BaseComponent):
  401. """padding image for model with FPN , instead PadBatch(pad_to_stride, pad_gt) in original config
  402. Args:
  403. stride (bool): model with FPN need image shape % stride == 0
  404. """
  405. INPUT_KEYS = "img"
  406. OUTPUT_KEYS = "img"
  407. DEAULT_INPUTS = {"img": "img"}
  408. DEAULT_OUTPUTS = {"img": "img"}
  409. def __init__(self, stride=0):
  410. super().__init__()
  411. self.coarsest_stride = stride
  412. def apply(self, img):
  413. """
  414. Args:
  415. im (np.ndarray): image (np.ndarray)
  416. Returns:
  417. im (np.ndarray): processed image (np.ndarray)
  418. """
  419. im = img
  420. coarsest_stride = self.coarsest_stride
  421. if coarsest_stride <= 0:
  422. return {"img": im}
  423. im_c, im_h, im_w = im.shape
  424. pad_h = int(np.ceil(float(im_h) / coarsest_stride) * coarsest_stride)
  425. pad_w = int(np.ceil(float(im_w) / coarsest_stride) * coarsest_stride)
  426. padding_im = np.zeros((im_c, pad_h, pad_w), dtype=np.float32)
  427. padding_im[:, :im_h, :im_w] = im
  428. return {"img": padding_im}
  429. class Normalize(BaseComponent):
  430. """Normalize the image."""
  431. INPUT_KEYS = "img"
  432. OUTPUT_KEYS = "img"
  433. DEAULT_INPUTS = {"img": "img"}
  434. DEAULT_OUTPUTS = {"img": "img"}
  435. def __init__(self, scale=1.0 / 255, mean=0.5, std=0.5, preserve_dtype=False):
  436. """
  437. Initialize the instance.
  438. Args:
  439. scale (float, optional): Scaling factor to apply to the image before
  440. applying normalization. Default: 1/255.
  441. mean (float|tuple|list, optional): Means for each channel of the image.
  442. Default: 0.5.
  443. std (float|tuple|list, optional): Standard deviations for each channel
  444. of the image. Default: 0.5.
  445. preserve_dtype (bool, optional): Whether to preserve the original dtype
  446. of the image.
  447. """
  448. super().__init__()
  449. self.scale = np.float32(scale)
  450. if isinstance(mean, float):
  451. mean = [mean]
  452. self.mean = np.asarray(mean).astype("float32")
  453. if isinstance(std, float):
  454. std = [std]
  455. self.std = np.asarray(std).astype("float32")
  456. self.preserve_dtype = preserve_dtype
  457. def apply(self, img):
  458. """apply"""
  459. old_type = img.dtype
  460. # XXX: If `old_type` has higher precision than float32,
  461. # we will lose some precision.
  462. img = img.astype("float32", copy=False)
  463. img *= self.scale
  464. img -= self.mean
  465. img /= self.std
  466. if self.preserve_dtype:
  467. img = img.astype(old_type, copy=False)
  468. return {"img": img}
  469. class ToCHWImage(BaseComponent):
  470. """Reorder the dimensions of the image from HWC to CHW."""
  471. INPUT_KEYS = "img"
  472. OUTPUT_KEYS = "img"
  473. DEAULT_INPUTS = {"img": "img"}
  474. DEAULT_OUTPUTS = {"img": "img"}
  475. def apply(self, img):
  476. """apply"""
  477. img = img.transpose((2, 0, 1))
  478. return {"img": img}