crop_image_regions.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. from .base_operator import BaseOperator
  15. import numpy as np
  16. from ....utils.io import ImageReader
  17. import copy
  18. import cv2
  19. from .seal_det_warp import AutoRectifier
  20. from shapely.geometry import Polygon
  21. from numpy.linalg import norm
  22. from typing import Tuple
  23. class CropByBoxes(BaseOperator):
  24. """Crop Image by Boxes"""
  25. entities = "CropByBoxes"
  26. def __init__(self) -> None:
  27. """Initializes the class."""
  28. super().__init__()
  29. def __call__(self, img: np.ndarray, boxes: list[dict]) -> list[dict]:
  30. """
  31. Process the input image and bounding boxes to produce a list of cropped images
  32. with their corresponding bounding box coordinates and labels.
  33. Args:
  34. img (np.ndarray): The input image as a NumPy array.
  35. boxes (list[dict]): A list of dictionaries, each containing bounding box
  36. information including 'cls_id' (class ID), 'coordinate' (bounding box
  37. coordinates as a list or tuple, left, top, right, bottom),
  38. and optionally 'label' (label text).
  39. Returns:
  40. list[dict]: A list of dictionaries, each containing a cropped image ('img'),
  41. the original bounding box coordinates ('box'), and the label ('label').
  42. """
  43. output_list = []
  44. for bbox_info in boxes:
  45. label_id = bbox_info["cls_id"]
  46. box = bbox_info["coordinate"]
  47. label = bbox_info.get("label", label_id)
  48. xmin, ymin, xmax, ymax = [int(i) for i in box]
  49. img_crop = img[ymin:ymax, xmin:xmax].copy()
  50. output_list.append({"img": img_crop, "box": box, "label": label})
  51. return output_list
  52. class CropByPolys(BaseOperator):
  53. """Crop Image by Polys"""
  54. entities = "CropByPolys"
  55. def __init__(self, det_box_type: str = "quad") -> None:
  56. """
  57. Initializes the operator with a default detection box type.
  58. Args:
  59. det_box_type (str, optional): The type of detection box, quad or poly. Defaults to "quad".
  60. """
  61. super().__init__()
  62. self.det_box_type = det_box_type
  63. def __call__(self, img: np.ndarray, dt_polys: list[list]) -> list[dict]:
  64. """
  65. Call method to crop images based on detection boxes.
  66. Args:
  67. img (nd.ndarray): The input image.
  68. dt_polys (list[list]): List of detection polygons.
  69. Returns:
  70. list[dict]: A list of dictionaries containing cropped images and their sizes.
  71. Raises:
  72. NotImplementedError: If det_box_type is not 'quad' or 'poly'.
  73. """
  74. if self.det_box_type == "quad":
  75. dt_boxes = np.array(dt_polys)
  76. output_list = []
  77. for bno in range(len(dt_boxes)):
  78. tmp_box = copy.deepcopy(dt_boxes[bno])
  79. img_crop = self.get_minarea_rect_crop(img, tmp_box)
  80. output_list.append(
  81. {
  82. "img": img_crop,
  83. "img_size": [img_crop.shape[1], img_crop.shape[0]],
  84. }
  85. )
  86. elif self.det_box_type == "poly":
  87. output_list = []
  88. dt_boxes = dt_polys
  89. for bno in range(len(dt_boxes)):
  90. tmp_box = copy.deepcopy(dt_boxes[bno])
  91. img_crop = self.get_poly_rect_crop(img.copy(), tmp_box)
  92. output_list.append(
  93. {
  94. "img": img_crop,
  95. "img_size": [img_crop.shape[1], img_crop.shape[0]],
  96. }
  97. )
  98. else:
  99. raise NotImplementedError
  100. return output_list
  101. def get_minarea_rect_crop(self, img: np.ndarray, points: np.ndarray) -> np.ndarray:
  102. """
  103. Get the minimum area rectangle crop from the given image and points.
  104. Args:
  105. img (np.ndarray): The input image.
  106. points (np.ndarray): A list of points defining the shape to be cropped.
  107. Returns:
  108. np.ndarray: The cropped image with the minimum area rectangle.
  109. """
  110. bounding_box = cv2.minAreaRect(np.array(points).astype(np.int32))
  111. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  112. index_a, index_b, index_c, index_d = 0, 1, 2, 3
  113. if points[1][1] > points[0][1]:
  114. index_a = 0
  115. index_d = 1
  116. else:
  117. index_a = 1
  118. index_d = 0
  119. if points[3][1] > points[2][1]:
  120. index_b = 2
  121. index_c = 3
  122. else:
  123. index_b = 3
  124. index_c = 2
  125. box = [points[index_a], points[index_b], points[index_c], points[index_d]]
  126. crop_img = self.get_rotate_crop_image(img, np.array(box))
  127. return crop_img
  128. def get_rotate_crop_image(self, img: np.ndarray, points: list) -> np.ndarray:
  129. """
  130. Crop and rotate the input image based on the given four points to form a perspective-transformed image.
  131. Args:
  132. img (np.ndarray): The input image array.
  133. points (list): A list of four 2D points defining the crop region in the image.
  134. Returns:
  135. np.ndarray: The transformed image array.
  136. """
  137. assert len(points) == 4, "shape of points must be 4*2"
  138. img_crop_width = int(
  139. max(
  140. np.linalg.norm(points[0] - points[1]),
  141. np.linalg.norm(points[2] - points[3]),
  142. )
  143. )
  144. img_crop_height = int(
  145. max(
  146. np.linalg.norm(points[0] - points[3]),
  147. np.linalg.norm(points[1] - points[2]),
  148. )
  149. )
  150. pts_std = np.float32(
  151. [
  152. [0, 0],
  153. [img_crop_width, 0],
  154. [img_crop_width, img_crop_height],
  155. [0, img_crop_height],
  156. ]
  157. )
  158. M = cv2.getPerspectiveTransform(points, pts_std)
  159. dst_img = cv2.warpPerspective(
  160. img,
  161. M,
  162. (img_crop_width, img_crop_height),
  163. borderMode=cv2.BORDER_REPLICATE,
  164. flags=cv2.INTER_CUBIC,
  165. )
  166. dst_img_height, dst_img_width = dst_img.shape[0:2]
  167. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  168. dst_img = np.rot90(dst_img)
  169. return dst_img
  170. def reorder_poly_edge(
  171. self, points: np.ndarray
  172. ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
  173. """Get the respective points composing head edge, tail edge, top
  174. sideline and bottom sideline.
  175. Args:
  176. points (ndarray): The points composing a text polygon.
  177. Returns:
  178. head_edge (ndarray): The two points composing the head edge of text
  179. polygon.
  180. tail_edge (ndarray): The two points composing the tail edge of text
  181. polygon.
  182. top_sideline (ndarray): The points composing top curved sideline of
  183. text polygon.
  184. bot_sideline (ndarray): The points composing bottom curved sideline
  185. of text polygon.
  186. """
  187. assert points.ndim == 2
  188. assert points.shape[0] >= 4
  189. assert points.shape[1] == 2
  190. orientation_thr = 2.0 # 一个经验超参数
  191. head_inds, tail_inds = self.find_head_tail(points, orientation_thr)
  192. head_edge, tail_edge = points[head_inds], points[tail_inds]
  193. pad_points = np.vstack([points, points])
  194. if tail_inds[1] < 1:
  195. tail_inds[1] = len(points)
  196. sideline1 = pad_points[head_inds[1] : tail_inds[1]]
  197. sideline2 = pad_points[tail_inds[1] : (head_inds[1] + len(points))]
  198. return head_edge, tail_edge, sideline1, sideline2
  199. def vector_slope(self, vec: list) -> float:
  200. """
  201. Calculate the slope of a vector in 2D space.
  202. Args:
  203. vec (list): A list of two elements representing the coordinates of the vector.
  204. Returns:
  205. float: The slope of the vector.
  206. Raises:
  207. AssertionError: If the length of the vector is not equal to 2.
  208. """
  209. assert len(vec) == 2
  210. return abs(vec[1] / (vec[0] + 1e-8))
  211. def find_head_tail(
  212. self, points: np.ndarray, orientation_thr: float
  213. ) -> tuple[list, list]:
  214. """Find the head edge and tail edge of a text polygon.
  215. Args:
  216. points (ndarray): The points composing a text polygon.
  217. orientation_thr (float): The threshold for distinguishing between
  218. head edge and tail edge among the horizontal and vertical edges
  219. of a quadrangle.
  220. Returns:
  221. head_inds (list): The indexes of two points composing head edge.
  222. tail_inds (list): The indexes of two points composing tail edge.
  223. """
  224. assert points.ndim == 2
  225. assert points.shape[0] >= 4
  226. assert points.shape[1] == 2
  227. assert isinstance(orientation_thr, float)
  228. if len(points) > 4:
  229. pad_points = np.vstack([points, points[0]])
  230. edge_vec = pad_points[1:] - pad_points[:-1]
  231. theta_sum = []
  232. adjacent_vec_theta = []
  233. for i, edge_vec1 in enumerate(edge_vec):
  234. adjacent_ind = [x % len(edge_vec) for x in [i - 1, i + 1]]
  235. adjacent_edge_vec = edge_vec[adjacent_ind]
  236. temp_theta_sum = np.sum(self.vector_angle(edge_vec1, adjacent_edge_vec))
  237. temp_adjacent_theta = self.vector_angle(
  238. adjacent_edge_vec[0], adjacent_edge_vec[1]
  239. )
  240. theta_sum.append(temp_theta_sum)
  241. adjacent_vec_theta.append(temp_adjacent_theta)
  242. theta_sum_score = np.array(theta_sum) / np.pi
  243. adjacent_theta_score = np.array(adjacent_vec_theta) / np.pi
  244. poly_center = np.mean(points, axis=0)
  245. edge_dist = np.maximum(
  246. norm(pad_points[1:] - poly_center, axis=-1),
  247. norm(pad_points[:-1] - poly_center, axis=-1),
  248. )
  249. dist_score = edge_dist / np.max(edge_dist)
  250. position_score = np.zeros(len(edge_vec))
  251. score = 0.5 * theta_sum_score + 0.15 * adjacent_theta_score
  252. score += 0.35 * dist_score
  253. if len(points) % 2 == 0:
  254. position_score[(len(score) // 2 - 1)] += 1
  255. position_score[-1] += 1
  256. score += 0.1 * position_score
  257. pad_score = np.concatenate([score, score])
  258. score_matrix = np.zeros((len(score), len(score) - 3))
  259. x = np.arange(len(score) - 3) / float(len(score) - 4)
  260. gaussian = (
  261. 1.0
  262. / (np.sqrt(2.0 * np.pi) * 0.5)
  263. * np.exp(-np.power((x - 0.5) / 0.5, 2.0) / 2)
  264. )
  265. gaussian = gaussian / np.max(gaussian)
  266. for i in range(len(score)):
  267. score_matrix[i, :] = (
  268. score[i]
  269. + pad_score[(i + 2) : (i + len(score) - 1)] * gaussian * 0.3
  270. )
  271. head_start, tail_increment = np.unravel_index(
  272. score_matrix.argmax(), score_matrix.shape
  273. )
  274. tail_start = (head_start + tail_increment + 2) % len(points)
  275. head_end = (head_start + 1) % len(points)
  276. tail_end = (tail_start + 1) % len(points)
  277. if head_end > tail_end:
  278. head_start, tail_start = tail_start, head_start
  279. head_end, tail_end = tail_end, head_end
  280. head_inds = [head_start, head_end]
  281. tail_inds = [tail_start, tail_end]
  282. else:
  283. if self.vector_slope(points[1] - points[0]) + self.vector_slope(
  284. points[3] - points[2]
  285. ) < self.vector_slope(points[2] - points[1]) + self.vector_slope(
  286. points[0] - points[3]
  287. ):
  288. horizontal_edge_inds = [[0, 1], [2, 3]]
  289. vertical_edge_inds = [[3, 0], [1, 2]]
  290. else:
  291. horizontal_edge_inds = [[3, 0], [1, 2]]
  292. vertical_edge_inds = [[0, 1], [2, 3]]
  293. vertical_len_sum = norm(
  294. points[vertical_edge_inds[0][0]] - points[vertical_edge_inds[0][1]]
  295. ) + norm(
  296. points[vertical_edge_inds[1][0]] - points[vertical_edge_inds[1][1]]
  297. )
  298. horizontal_len_sum = norm(
  299. points[horizontal_edge_inds[0][0]] - points[horizontal_edge_inds[0][1]]
  300. ) + norm(
  301. points[horizontal_edge_inds[1][0]] - points[horizontal_edge_inds[1][1]]
  302. )
  303. if vertical_len_sum > horizontal_len_sum * orientation_thr:
  304. head_inds = horizontal_edge_inds[0]
  305. tail_inds = horizontal_edge_inds[1]
  306. else:
  307. head_inds = vertical_edge_inds[0]
  308. tail_inds = vertical_edge_inds[1]
  309. return head_inds, tail_inds
  310. def vector_angle(self, vec1: np.ndarray, vec2: np.ndarray) -> float:
  311. """
  312. Calculate the angle between two vectors.
  313. Args:
  314. vec1 (ndarray): The first vector.
  315. vec2 (ndarray): The second vector.
  316. Returns:
  317. float: The angle between the two vectors in radians.
  318. """
  319. if vec1.ndim > 1:
  320. unit_vec1 = vec1 / (norm(vec1, axis=-1) + 1e-8).reshape((-1, 1))
  321. else:
  322. unit_vec1 = vec1 / (norm(vec1, axis=-1) + 1e-8)
  323. if vec2.ndim > 1:
  324. unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8).reshape((-1, 1))
  325. else:
  326. unit_vec2 = vec2 / (norm(vec2, axis=-1) + 1e-8)
  327. return np.arccos(np.clip(np.sum(unit_vec1 * unit_vec2, axis=-1), -1.0, 1.0))
  328. def get_minarea_rect(
  329. self, img: np.ndarray, points: np.ndarray
  330. ) -> tuple[np.ndarray, list]:
  331. """
  332. Get the minimum area rectangle for the given points and crop the image accordingly.
  333. Args:
  334. img (np.ndarray): The input image.
  335. points (np.ndarray): The points to compute the minimum area rectangle for.
  336. Returns:
  337. tuple[np.ndarray, list]: The cropped image,
  338. and the list of points in the order of the bounding box.
  339. """
  340. bounding_box = cv2.minAreaRect(points)
  341. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  342. index_a, index_b, index_c, index_d = 0, 1, 2, 3
  343. if points[1][1] > points[0][1]:
  344. index_a = 0
  345. index_d = 1
  346. else:
  347. index_a = 1
  348. index_d = 0
  349. if points[3][1] > points[2][1]:
  350. index_b = 2
  351. index_c = 3
  352. else:
  353. index_b = 3
  354. index_c = 2
  355. box = [points[index_a], points[index_b], points[index_c], points[index_d]]
  356. crop_img = self.get_rotate_crop_image(img, np.array(box))
  357. return crop_img, box
  358. def sample_points_on_bbox_bp(self, line, n=50):
  359. """Resample n points on a line.
  360. Args:
  361. line (ndarray): The points composing a line.
  362. n (int): The resampled points number.
  363. Returns:
  364. resampled_line (ndarray): The points composing the resampled line.
  365. """
  366. from numpy.linalg import norm
  367. # 断言检查输入参数的有效性
  368. assert line.ndim == 2
  369. assert line.shape[0] >= 2
  370. assert line.shape[1] == 2
  371. assert isinstance(n, int)
  372. assert n > 0
  373. length_list = [norm(line[i + 1] - line[i]) for i in range(len(line) - 1)]
  374. total_length = sum(length_list)
  375. length_cumsum = np.cumsum([0.0] + length_list)
  376. delta_length = total_length / (float(n) + 1e-8)
  377. current_edge_ind = 0
  378. resampled_line = [line[0]]
  379. for i in range(1, n):
  380. current_line_len = i * delta_length
  381. while (
  382. current_edge_ind + 1 < len(length_cumsum)
  383. and current_line_len >= length_cumsum[current_edge_ind + 1]
  384. ):
  385. current_edge_ind += 1
  386. current_edge_end_shift = current_line_len - length_cumsum[current_edge_ind]
  387. if current_edge_ind >= len(length_list):
  388. break
  389. end_shift_ratio = current_edge_end_shift / length_list[current_edge_ind]
  390. current_point = (
  391. line[current_edge_ind]
  392. + (line[current_edge_ind + 1] - line[current_edge_ind])
  393. * end_shift_ratio
  394. )
  395. resampled_line.append(current_point)
  396. resampled_line.append(line[-1])
  397. resampled_line = np.array(resampled_line)
  398. return resampled_line
  399. def sample_points_on_bbox(self, line, n=50):
  400. """Resample n points on a line.
  401. Args:
  402. line (ndarray): The points composing a line.
  403. n (int): The resampled points number.
  404. Returns:
  405. resampled_line (ndarray): The points composing the resampled line.
  406. """
  407. assert line.ndim == 2
  408. assert line.shape[0] >= 2
  409. assert line.shape[1] == 2
  410. assert isinstance(n, int)
  411. assert n > 0
  412. length_list = [norm(line[i + 1] - line[i]) for i in range(len(line) - 1)]
  413. total_length = sum(length_list)
  414. mean_length = total_length / (len(length_list) + 1e-8)
  415. group = [[0]]
  416. for i in range(len(length_list)):
  417. point_id = i + 1
  418. if length_list[i] < 0.9 * mean_length:
  419. for g in group:
  420. if i in g:
  421. g.append(point_id)
  422. break
  423. else:
  424. g = [point_id]
  425. group.append(g)
  426. top_tail_len = norm(line[0] - line[-1])
  427. if top_tail_len < 0.9 * mean_length:
  428. group[0].extend(g)
  429. group.remove(g)
  430. mean_positions = []
  431. for indices in group:
  432. x_sum = 0
  433. y_sum = 0
  434. for index in indices:
  435. x, y = line[index]
  436. x_sum += x
  437. y_sum += y
  438. num_points = len(indices)
  439. mean_x = x_sum / num_points
  440. mean_y = y_sum / num_points
  441. mean_positions.append((mean_x, mean_y))
  442. resampled_line = np.array(mean_positions)
  443. return resampled_line
  444. def get_poly_rect_crop(self, img, points):
  445. """
  446. 修改该函数,实现使用polygon,对不规则、弯曲文本的矫正以及crop
  447. args: img: 图片 ndarrary格式
  448. points: polygon格式的多点坐标 N*2 shape, ndarray格式
  449. return: 矫正后的图片 ndarray格式
  450. """
  451. points = np.array(points).astype(np.int32).reshape(-1, 2)
  452. temp_crop_img, temp_box = self.get_minarea_rect(img, points)
  453. # 计算最小外接矩形与polygon的IoU
  454. def get_union(pD, pG):
  455. return Polygon(pD).union(Polygon(pG)).area
  456. def get_intersection_over_union(pD, pG):
  457. return get_intersection(pD, pG) / (get_union(pD, pG) + 1e-10)
  458. def get_intersection(pD, pG):
  459. return Polygon(pD).intersection(Polygon(pG)).area
  460. cal_IoU = get_intersection_over_union(points, temp_box)
  461. if cal_IoU >= 0.7:
  462. points = self.sample_points_on_bbox_bp(points, 31)
  463. return temp_crop_img
  464. points_sample = self.sample_points_on_bbox(points)
  465. points_sample = points_sample.astype(np.int32)
  466. head_edge, tail_edge, top_line, bot_line = self.reorder_poly_edge(points_sample)
  467. resample_top_line = self.sample_points_on_bbox_bp(top_line, 15)
  468. resample_bot_line = self.sample_points_on_bbox_bp(bot_line, 15)
  469. sideline_mean_shift = np.mean(resample_top_line, axis=0) - np.mean(
  470. resample_bot_line, axis=0
  471. )
  472. if sideline_mean_shift[1] > 0:
  473. resample_bot_line, resample_top_line = resample_top_line, resample_bot_line
  474. rectifier = AutoRectifier()
  475. new_points = np.concatenate([resample_top_line, resample_bot_line])
  476. new_points_list = list(new_points.astype(np.float32).reshape(1, -1).tolist())
  477. if len(img.shape) == 2:
  478. img = np.stack((img,) * 3, axis=-1)
  479. img_crop, image = rectifier.run(img, new_points_list, mode="homography")
  480. return np.array(img_crop[0], dtype=np.uint8)