__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 os
  15. import math
  16. from pathlib import Path
  17. from copy import deepcopy
  18. import numpy as np
  19. import cv2
  20. from .....utils.download import download
  21. from .....utils.cache import CACHE_DIR
  22. from ....utils.io import ImageReader, ImageWriter
  23. from ...base import BaseComponent
  24. from . import funcs as F
  25. __all__ = [
  26. "ReadImage",
  27. "Flip",
  28. "Crop",
  29. "Resize",
  30. "ResizeByLong",
  31. "ResizeByShort",
  32. "Pad",
  33. "Normalize",
  34. "ToCHWImage",
  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(BaseComponent):
  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. "img_path": "img_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"]
  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__()
  71. self.batch_size = batch_size
  72. self.format = format
  73. flags = self._FLAGS_DICT[self.format]
  74. self._reader = ImageReader(backend="opencv", flags=flags)
  75. self._writer = ImageWriter(backend="opencv")
  76. def apply(self, img):
  77. """apply"""
  78. if not isinstance(img, str):
  79. img_path = (Path(CACHE_DIR) / "predict_input" / "tmp_img.jpg").as_posix()
  80. self._writer.write(img_path, img)
  81. yield [
  82. {
  83. "img_path": img_path,
  84. "img": img,
  85. "img_size": [img.shape[1], img.shape[0]],
  86. "ori_img": deepcopy(img),
  87. "ori_img_size": deepcopy([img.shape[1], img.shape[0]]),
  88. }
  89. ]
  90. else:
  91. img_path = img
  92. # XXX: auto download for url
  93. img_path = self._download_from_url(img_path)
  94. image_list = self._get_image_list(img_path)
  95. batch = []
  96. for img_path in image_list:
  97. img = self._read_img(img_path)
  98. batch.append(img)
  99. if len(batch) >= self.batch_size:
  100. yield batch
  101. batch = []
  102. if len(batch) > 0:
  103. yield batch
  104. def _read_img(self, img_path):
  105. blob = self._reader.read(img_path)
  106. if blob is None:
  107. raise Exception("Image read Error")
  108. if self.format == "RGB":
  109. if blob.ndim != 3:
  110. raise RuntimeError("Array is not 3-dimensional.")
  111. # BGR to RGB
  112. blob = blob[..., ::-1]
  113. return {
  114. "img_path": img_path,
  115. "img": blob,
  116. "img_size": [blob.shape[1], blob.shape[0]],
  117. "ori_img": deepcopy(blob),
  118. "ori_img_size": deepcopy([blob.shape[1], blob.shape[0]]),
  119. }
  120. def _download_from_url(self, in_path):
  121. if in_path.startswith("http"):
  122. file_name = Path(in_path).name
  123. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  124. download(in_path, save_path, overwrite=True)
  125. return save_path.as_posix()
  126. return in_path
  127. def _get_image_list(self, img_file):
  128. imgs_lists = []
  129. if img_file is None or not os.path.exists(img_file):
  130. raise Exception(f"Not found any img file in path: {img_file}")
  131. if os.path.isfile(img_file) and img_file.split(".")[-1] in self.SUFFIX:
  132. imgs_lists.append(img_file)
  133. elif os.path.isdir(img_file):
  134. for root, dirs, files in os.walk(img_file):
  135. for single_file in files:
  136. if single_file.split(".")[-1] in self.SUFFIX:
  137. imgs_lists.append(os.path.join(root, single_file))
  138. if len(imgs_lists) == 0:
  139. raise Exception("not found any img file in {}".format(img_file))
  140. imgs_lists = sorted(imgs_lists)
  141. return imgs_lists
  142. class GetImageInfo(BaseComponent):
  143. """Get Image Info"""
  144. INPUT_KEYS = "img"
  145. OUTPUT_KEYS = "img_size"
  146. DEAULT_INPUTS = {"img": "img"}
  147. DEAULT_OUTPUTS = {"img_size": "img_size"}
  148. def __init__(self):
  149. super().__init__()
  150. def apply(self, img):
  151. """apply"""
  152. return {"img_size": [img.shape[1], img.shape[0]]}
  153. class Flip(BaseComponent):
  154. """Flip the image vertically or horizontally."""
  155. INPUT_KEYS = "img"
  156. OUTPUT_KEYS = "img"
  157. DEAULT_INPUTS = {"img": "img"}
  158. DEAULT_OUTPUTS = {"img": "img"}
  159. def __init__(self, mode="H"):
  160. """
  161. Initialize the instance.
  162. Args:
  163. mode (str, optional): 'H' for horizontal flipping and 'V' for vertical
  164. flipping. Default: 'H'.
  165. """
  166. super().__init__()
  167. if mode not in ("H", "V"):
  168. raise ValueError("`mode` should be 'H' or 'V'.")
  169. self.mode = mode
  170. def apply(self, img):
  171. """apply"""
  172. if self.mode == "H":
  173. img = F.flip_h(img)
  174. elif self.mode == "V":
  175. img = F.flip_v(img)
  176. return {"img": img}
  177. class Crop(BaseComponent):
  178. """Crop region from the image."""
  179. INPUT_KEYS = "img"
  180. OUTPUT_KEYS = ["img", "img_size"]
  181. DEAULT_INPUTS = {"img": "img"}
  182. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  183. def __init__(self, crop_size, mode="C"):
  184. """
  185. Initialize the instance.
  186. Args:
  187. crop_size (list|tuple|int): Width and height of the region to crop.
  188. mode (str, optional): 'C' for cropping the center part and 'TL' for
  189. cropping the top left part. Default: 'C'.
  190. """
  191. super().__init__()
  192. if isinstance(crop_size, int):
  193. crop_size = [crop_size, crop_size]
  194. _check_image_size(crop_size)
  195. self.crop_size = crop_size
  196. if mode not in ("C", "TL"):
  197. raise ValueError("Unsupported interpolation method")
  198. self.mode = mode
  199. def apply(self, img):
  200. """apply"""
  201. h, w = img.shape[:2]
  202. cw, ch = self.crop_size
  203. if self.mode == "C":
  204. x1 = max(0, (w - cw) // 2)
  205. y1 = max(0, (h - ch) // 2)
  206. elif self.mode == "TL":
  207. x1, y1 = 0, 0
  208. x2 = min(w, x1 + cw)
  209. y2 = min(h, y1 + ch)
  210. coords = (x1, y1, x2, y2)
  211. if coords == (0, 0, w, h):
  212. raise ValueError(
  213. f"Input image ({w}, {h}) smaller than the target size ({cw}, {ch})."
  214. )
  215. img = F.slice(img, coords=coords)
  216. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  217. class _BaseResize(BaseComponent):
  218. _INTERP_DICT = {
  219. "NEAREST": cv2.INTER_NEAREST,
  220. "LINEAR": cv2.INTER_LINEAR,
  221. "CUBIC": cv2.INTER_CUBIC,
  222. "AREA": cv2.INTER_AREA,
  223. "LANCZOS4": cv2.INTER_LANCZOS4,
  224. }
  225. def __init__(self, size_divisor, interp):
  226. super().__init__()
  227. if size_divisor is not None:
  228. assert isinstance(
  229. size_divisor, int
  230. ), "`size_divisor` should be None or int."
  231. self.size_divisor = size_divisor
  232. try:
  233. interp = self._INTERP_DICT[interp]
  234. except KeyError:
  235. raise ValueError(
  236. "`interp` should be one of {}.".format(self._INTERP_DICT.keys())
  237. )
  238. self.interp = interp
  239. @staticmethod
  240. def _rescale_size(img_size, target_size):
  241. """rescale size"""
  242. scale = min(max(target_size) / max(img_size), min(target_size) / min(img_size))
  243. rescaled_size = [round(i * scale) for i in img_size]
  244. return rescaled_size, scale
  245. class Resize(_BaseResize):
  246. """Resize the image."""
  247. INPUT_KEYS = "img"
  248. OUTPUT_KEYS = ["img", "img_size", "scale_factors"]
  249. DEAULT_INPUTS = {"img": "img"}
  250. DEAULT_OUTPUTS = {
  251. "img": "img",
  252. "img_size": "img_size",
  253. "scale_factors": "scale_factors",
  254. }
  255. def __init__(
  256. self, target_size, keep_ratio=False, size_divisor=None, interp="LINEAR"
  257. ):
  258. """
  259. Initialize the instance.
  260. Args:
  261. target_size (list|tuple|int): Target width and height.
  262. keep_ratio (bool, optional): Whether to keep the aspect ratio of resized
  263. image. Default: False.
  264. size_divisor (int|None, optional): Divisor of resized image size.
  265. Default: None.
  266. interp (str, optional): Interpolation method. Choices are 'NEAREST',
  267. 'LINEAR', 'CUBIC', 'AREA', and 'LANCZOS4'. Default: 'LINEAR'.
  268. """
  269. super().__init__(size_divisor=size_divisor, interp=interp)
  270. if isinstance(target_size, int):
  271. target_size = [target_size, target_size]
  272. _check_image_size(target_size)
  273. self.target_size = target_size
  274. self.keep_ratio = keep_ratio
  275. def apply(self, img):
  276. """apply"""
  277. target_size = self.target_size
  278. original_size = img.shape[:2]
  279. if self.keep_ratio:
  280. h, w = img.shape[0:2]
  281. target_size, _ = self._rescale_size((w, h), self.target_size)
  282. if self.size_divisor:
  283. target_size = [
  284. math.ceil(i / self.size_divisor) * self.size_divisor
  285. for i in target_size
  286. ]
  287. img_scale_w, img_scale_h = [
  288. target_size[1] / original_size[1],
  289. target_size[0] / original_size[0],
  290. ]
  291. img = F.resize(img, target_size, interp=self.interp)
  292. return {
  293. "img": img,
  294. "img_size": [img.shape[1], img.shape[0]],
  295. "scale_factors": [img_scale_w, img_scale_h],
  296. }
  297. class ResizeByLong(_BaseResize):
  298. """
  299. Proportionally resize the image by specifying the target length of the
  300. longest side.
  301. """
  302. INPUT_KEYS = "img"
  303. OUTPUT_KEYS = ["img", "img_size"]
  304. DEAULT_INPUTS = {"img": "img"}
  305. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  306. def __init__(self, target_long_edge, size_divisor=None, interp="LINEAR"):
  307. """
  308. Initialize the instance.
  309. Args:
  310. target_long_edge (int): Target length of the longest side of image.
  311. size_divisor (int|None, optional): Divisor of resized image size.
  312. Default: None.
  313. interp (str, optional): Interpolation method. Choices are 'NEAREST',
  314. 'LINEAR', 'CUBIC', 'AREA', and 'LANCZOS4'. Default: 'LINEAR'.
  315. """
  316. super().__init__(size_divisor=size_divisor, interp=interp)
  317. self.target_long_edge = target_long_edge
  318. def apply(self, img):
  319. """apply"""
  320. h, w = img.shape[:2]
  321. scale = self.target_long_edge / max(h, w)
  322. h_resize = round(h * scale)
  323. w_resize = round(w * scale)
  324. if self.size_divisor is not None:
  325. h_resize = math.ceil(h_resize / self.size_divisor) * self.size_divisor
  326. w_resize = math.ceil(w_resize / self.size_divisor) * self.size_divisor
  327. img = F.resize(img, (w_resize, h_resize), interp=self.interp)
  328. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  329. class ResizeByShort(_BaseResize):
  330. """
  331. Proportionally resize the image by specifying the target length of the
  332. shortest side.
  333. """
  334. INPUT_KEYS = "img"
  335. OUTPUT_KEYS = ["img", "img_size"]
  336. DEAULT_INPUTS = {"img": "img"}
  337. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  338. def __init__(self, target_short_edge, size_divisor=None, interp="LINEAR"):
  339. """
  340. Initialize the instance.
  341. Args:
  342. target_short_edge (int): Target length of the shortest side of image.
  343. size_divisor (int|None, optional): Divisor of resized image size.
  344. Default: None.
  345. interp (str, optional): Interpolation method. Choices are 'NEAREST',
  346. 'LINEAR', 'CUBIC', 'AREA', and 'LANCZOS4'. Default: 'LINEAR'.
  347. """
  348. super().__init__(size_divisor=size_divisor, interp=interp)
  349. self.target_short_edge = target_short_edge
  350. def apply(self, img):
  351. """apply"""
  352. h, w = img.shape[:2]
  353. scale = self.target_short_edge / min(h, w)
  354. h_resize = round(h * scale)
  355. w_resize = round(w * scale)
  356. if self.size_divisor is not None:
  357. h_resize = math.ceil(h_resize / self.size_divisor) * self.size_divisor
  358. w_resize = math.ceil(w_resize / self.size_divisor) * self.size_divisor
  359. img = F.resize(img, (w_resize, h_resize), interp=self.interp)
  360. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  361. class Pad(BaseComponent):
  362. """Pad the image."""
  363. INPUT_KEYS = "img"
  364. OUTPUT_KEYS = ["img", "img_size"]
  365. DEAULT_INPUTS = {"img": "img"}
  366. DEAULT_OUTPUTS = {"img": "img", "img_size": "img_size"}
  367. def __init__(self, target_size, val=127.5):
  368. """
  369. Initialize the instance.
  370. Args:
  371. target_size (list|tuple|int): Target width and height of the image after
  372. padding.
  373. val (float, optional): Value to fill the padded area. Default: 127.5.
  374. """
  375. super().__init__()
  376. if isinstance(target_size, int):
  377. target_size = [target_size, target_size]
  378. _check_image_size(target_size)
  379. self.target_size = target_size
  380. self.val = val
  381. def apply(self, img):
  382. """apply"""
  383. h, w = img.shape[:2]
  384. tw, th = self.target_size
  385. ph = th - h
  386. pw = tw - w
  387. if ph < 0 or pw < 0:
  388. raise ValueError(
  389. f"Input image ({w}, {h}) smaller than the target size ({tw}, {th})."
  390. )
  391. else:
  392. img = F.pad(img, pad=(0, ph, 0, pw), val=self.val)
  393. return {"img": img, "img_size": [img.shape[1], img.shape[0]]}
  394. class Normalize(BaseComponent):
  395. """Normalize the image."""
  396. INPUT_KEYS = "img"
  397. OUTPUT_KEYS = "img"
  398. DEAULT_INPUTS = {"img": "img"}
  399. DEAULT_OUTPUTS = {"img": "img"}
  400. def __init__(self, scale=1.0 / 255, mean=0.5, std=0.5, preserve_dtype=False):
  401. """
  402. Initialize the instance.
  403. Args:
  404. scale (float, optional): Scaling factor to apply to the image before
  405. applying normalization. Default: 1/255.
  406. mean (float|tuple|list, optional): Means for each channel of the image.
  407. Default: 0.5.
  408. std (float|tuple|list, optional): Standard deviations for each channel
  409. of the image. Default: 0.5.
  410. preserve_dtype (bool, optional): Whether to preserve the original dtype
  411. of the image.
  412. """
  413. super().__init__()
  414. self.scale = np.float32(scale)
  415. if isinstance(mean, float):
  416. mean = [mean]
  417. self.mean = np.asarray(mean).astype("float32")
  418. if isinstance(std, float):
  419. std = [std]
  420. self.std = np.asarray(std).astype("float32")
  421. self.preserve_dtype = preserve_dtype
  422. def apply(self, img):
  423. """apply"""
  424. old_type = img.dtype
  425. # XXX: If `old_type` has higher precision than float32,
  426. # we will lose some precision.
  427. img = img.astype("float32", copy=False)
  428. img *= self.scale
  429. img -= self.mean
  430. img /= self.std
  431. if self.preserve_dtype:
  432. img = img.astype(old_type, copy=False)
  433. return {"img": img}
  434. class ToCHWImage(BaseComponent):
  435. """Reorder the dimensions of the image from HWC to CHW."""
  436. INPUT_KEYS = "img"
  437. OUTPUT_KEYS = "img"
  438. DEAULT_INPUTS = {"img": "img"}
  439. DEAULT_OUTPUTS = {"img": "img"}
  440. def apply(self, img):
  441. """apply"""
  442. img = img.transpose((2, 0, 1))
  443. return {"img": img}