ct_process.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # copyright (c) 2020 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 cv2
  16. import paddle
  17. import random
  18. import pyclipper
  19. import numpy as np
  20. from PIL import Image
  21. import paddle.vision.transforms as transforms
  22. from ppocr.utils.utility import check_install
  23. class RandomScale:
  24. def __init__(self, short_size=640, **kwargs):
  25. self.short_size = short_size
  26. def scale_aligned(self, img, scale):
  27. oh, ow = img.shape[0:2]
  28. h = int(oh * scale + 0.5)
  29. w = int(ow * scale + 0.5)
  30. if h % 32 != 0:
  31. h = h + (32 - h % 32)
  32. if w % 32 != 0:
  33. w = w + (32 - w % 32)
  34. img = cv2.resize(img, dsize=(w, h))
  35. factor_h = h / oh
  36. factor_w = w / ow
  37. return img, factor_h, factor_w
  38. def __call__(self, data):
  39. img = data["image"]
  40. h, w = img.shape[0:2]
  41. random_scale = np.array([0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3])
  42. scale = (np.random.choice(random_scale) * self.short_size) / min(h, w)
  43. img, factor_h, factor_w = self.scale_aligned(img, scale)
  44. data["scale_factor"] = (factor_w, factor_h)
  45. data["image"] = img
  46. return data
  47. class MakeShrink:
  48. def __init__(self, kernel_scale=0.7, **kwargs):
  49. self.kernel_scale = kernel_scale
  50. def dist(self, a, b):
  51. return np.linalg.norm((a - b), ord=2, axis=0)
  52. def perimeter(self, bbox):
  53. peri = 0.0
  54. for i in range(bbox.shape[0]):
  55. peri += self.dist(bbox[i], bbox[(i + 1) % bbox.shape[0]])
  56. return peri
  57. def shrink(self, bboxes, rate, max_shr=20):
  58. check_install("Polygon", "Polygon3")
  59. import Polygon as plg
  60. rate = rate * rate
  61. shrinked_bboxes = []
  62. for bbox in bboxes:
  63. area = plg.Polygon(bbox).area()
  64. peri = self.perimeter(bbox)
  65. try:
  66. pco = pyclipper.PyclipperOffset()
  67. pco.AddPath(bbox, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
  68. offset = min(int(area * (1 - rate) / (peri + 0.001) + 0.5), max_shr)
  69. shrinked_bbox = pco.Execute(-offset)
  70. if len(shrinked_bbox) == 0:
  71. shrinked_bboxes.append(bbox)
  72. continue
  73. shrinked_bbox = np.array(shrinked_bbox[0])
  74. if shrinked_bbox.shape[0] <= 2:
  75. shrinked_bboxes.append(bbox)
  76. continue
  77. shrinked_bboxes.append(shrinked_bbox)
  78. except Exception as e:
  79. shrinked_bboxes.append(bbox)
  80. return shrinked_bboxes
  81. def __call__(self, data):
  82. img = data["image"]
  83. bboxes = data["polys"]
  84. words = data["texts"]
  85. scale_factor = data["scale_factor"]
  86. gt_instance = np.zeros(img.shape[0:2], dtype="uint8") # h,w
  87. training_mask = np.ones(img.shape[0:2], dtype="uint8")
  88. training_mask_distance = np.ones(img.shape[0:2], dtype="uint8")
  89. for i in range(len(bboxes)):
  90. bboxes[i] = np.reshape(
  91. bboxes[i]
  92. * ([scale_factor[0], scale_factor[1]] * (bboxes[i].shape[0] // 2)),
  93. (bboxes[i].shape[0] // 2, 2),
  94. ).astype("int32")
  95. for i in range(len(bboxes)):
  96. # different value for different bbox
  97. cv2.drawContours(gt_instance, [bboxes[i]], -1, i + 1, -1)
  98. # set training mask to 0
  99. cv2.drawContours(training_mask, [bboxes[i]], -1, 0, -1)
  100. # for not accurate annotation, use training_mask_distance
  101. if words[i] == "###" or words[i] == "???":
  102. cv2.drawContours(training_mask_distance, [bboxes[i]], -1, 0, -1)
  103. # make shrink
  104. gt_kernel_instance = np.zeros(img.shape[0:2], dtype="uint8")
  105. kernel_bboxes = self.shrink(bboxes, self.kernel_scale)
  106. for i in range(len(bboxes)):
  107. cv2.drawContours(gt_kernel_instance, [kernel_bboxes[i]], -1, i + 1, -1)
  108. # for training mask, kernel and background= 1, box region=0
  109. if words[i] != "###" and words[i] != "???":
  110. cv2.drawContours(training_mask, [kernel_bboxes[i]], -1, 1, -1)
  111. gt_kernel = gt_kernel_instance.copy()
  112. # for gt_kernel, kernel = 1
  113. gt_kernel[gt_kernel > 0] = 1
  114. # shrink 2 times
  115. tmp1 = gt_kernel_instance.copy()
  116. erode_kernel = np.ones((3, 3), np.uint8)
  117. tmp1 = cv2.erode(tmp1, erode_kernel, iterations=1)
  118. tmp2 = tmp1.copy()
  119. tmp2 = cv2.erode(tmp2, erode_kernel, iterations=1)
  120. # compute text region
  121. gt_kernel_inner = tmp1 - tmp2
  122. # gt_instance: text instance, bg=0, diff word use diff value
  123. # training_mask: text instance mask, word=0,kernel and bg=1
  124. # gt_kernel_instance: text kernel instance, bg=0, diff word use diff value
  125. # gt_kernel: text_kernel, bg=0,diff word use same value
  126. # gt_kernel_inner: text kernel reference
  127. # training_mask_distance: word without anno = 0, else 1
  128. data["image"] = [
  129. img,
  130. gt_instance,
  131. training_mask,
  132. gt_kernel_instance,
  133. gt_kernel,
  134. gt_kernel_inner,
  135. training_mask_distance,
  136. ]
  137. return data
  138. class GroupRandomHorizontalFlip:
  139. def __init__(self, p=0.5, **kwargs):
  140. self.p = p
  141. def __call__(self, data):
  142. imgs = data["image"]
  143. if random.random() < self.p:
  144. for i in range(len(imgs)):
  145. imgs[i] = np.flip(imgs[i], axis=1).copy()
  146. data["image"] = imgs
  147. return data
  148. class GroupRandomRotate:
  149. def __init__(self, **kwargs):
  150. pass
  151. def __call__(self, data):
  152. imgs = data["image"]
  153. max_angle = 10
  154. angle = random.random() * 2 * max_angle - max_angle
  155. for i in range(len(imgs)):
  156. img = imgs[i]
  157. w, h = img.shape[:2]
  158. rotation_matrix = cv2.getRotationMatrix2D((h / 2, w / 2), angle, 1)
  159. img_rotation = cv2.warpAffine(
  160. img, rotation_matrix, (h, w), flags=cv2.INTER_NEAREST
  161. )
  162. imgs[i] = img_rotation
  163. data["image"] = imgs
  164. return data
  165. class GroupRandomCropPadding:
  166. def __init__(self, target_size=(640, 640), **kwargs):
  167. self.target_size = target_size
  168. def __call__(self, data):
  169. imgs = data["image"]
  170. h, w = imgs[0].shape[0:2]
  171. t_w, t_h = self.target_size
  172. p_w, p_h = self.target_size
  173. if w == t_w and h == t_h:
  174. return data
  175. t_h = t_h if t_h < h else h
  176. t_w = t_w if t_w < w else w
  177. if random.random() > 3.0 / 8.0 and np.max(imgs[1]) > 0:
  178. # make sure to crop the text region
  179. tl = np.min(np.where(imgs[1] > 0), axis=1) - (t_h, t_w)
  180. tl[tl < 0] = 0
  181. br = np.max(np.where(imgs[1] > 0), axis=1) - (t_h, t_w)
  182. br[br < 0] = 0
  183. br[0] = min(br[0], h - t_h)
  184. br[1] = min(br[1], w - t_w)
  185. i = random.randint(tl[0], br[0]) if tl[0] < br[0] else 0
  186. j = random.randint(tl[1], br[1]) if tl[1] < br[1] else 0
  187. else:
  188. i = random.randint(0, h - t_h) if h - t_h > 0 else 0
  189. j = random.randint(0, w - t_w) if w - t_w > 0 else 0
  190. n_imgs = []
  191. for idx in range(len(imgs)):
  192. if len(imgs[idx].shape) == 3:
  193. s3_length = int(imgs[idx].shape[-1])
  194. img = imgs[idx][i : i + t_h, j : j + t_w, :]
  195. img_p = cv2.copyMakeBorder(
  196. img,
  197. 0,
  198. p_h - t_h,
  199. 0,
  200. p_w - t_w,
  201. borderType=cv2.BORDER_CONSTANT,
  202. value=tuple(0 for i in range(s3_length)),
  203. )
  204. else:
  205. img = imgs[idx][i : i + t_h, j : j + t_w]
  206. img_p = cv2.copyMakeBorder(
  207. img,
  208. 0,
  209. p_h - t_h,
  210. 0,
  211. p_w - t_w,
  212. borderType=cv2.BORDER_CONSTANT,
  213. value=(0,),
  214. )
  215. n_imgs.append(img_p)
  216. data["image"] = n_imgs
  217. return data
  218. class MakeCentripetalShift:
  219. def __init__(self, **kwargs):
  220. pass
  221. def jaccard(self, As, Bs):
  222. A = As.shape[0] # small
  223. B = Bs.shape[0] # large
  224. dis = np.sqrt(
  225. np.sum(
  226. (
  227. As[:, np.newaxis, :].repeat(B, axis=1)
  228. - Bs[np.newaxis, :, :].repeat(A, axis=0)
  229. )
  230. ** 2,
  231. axis=-1,
  232. )
  233. )
  234. ind = np.argmin(dis, axis=-1)
  235. return ind
  236. def __call__(self, data):
  237. imgs = data["image"]
  238. (
  239. img,
  240. gt_instance,
  241. training_mask,
  242. gt_kernel_instance,
  243. gt_kernel,
  244. gt_kernel_inner,
  245. training_mask_distance,
  246. ) = (imgs[0], imgs[1], imgs[2], imgs[3], imgs[4], imgs[5], imgs[6])
  247. max_instance = np.max(gt_instance) # num bbox
  248. # make centripetal shift
  249. gt_distance = np.zeros((2, *img.shape[0:2]), dtype=np.float32)
  250. for i in range(1, max_instance + 1):
  251. # kernel_reference
  252. ind = gt_kernel_inner == i
  253. if np.sum(ind) == 0:
  254. training_mask[gt_instance == i] = 0
  255. training_mask_distance[gt_instance == i] = 0
  256. continue
  257. kpoints = (
  258. np.array(np.where(ind)).transpose((1, 0))[:, ::-1].astype("float32")
  259. )
  260. ind = (gt_instance == i) * (gt_kernel_instance == 0)
  261. if np.sum(ind) == 0:
  262. continue
  263. pixels = np.where(ind)
  264. points = np.array(pixels).transpose((1, 0))[:, ::-1].astype("float32")
  265. bbox_ind = self.jaccard(points, kpoints)
  266. offset_gt = kpoints[bbox_ind] - points
  267. gt_distance[:, pixels[0], pixels[1]] = offset_gt.T * 0.1
  268. img = Image.fromarray(img)
  269. img = img.convert("RGB")
  270. data["image"] = img
  271. data["gt_kernel"] = gt_kernel.astype("int64")
  272. data["training_mask"] = training_mask.astype("int64")
  273. data["gt_instance"] = gt_instance.astype("int64")
  274. data["gt_kernel_instance"] = gt_kernel_instance.astype("int64")
  275. data["training_mask_distance"] = training_mask_distance.astype("int64")
  276. data["gt_distance"] = gt_distance.astype("float32")
  277. return data
  278. class ScaleAlignedShort:
  279. def __init__(self, short_size=640, **kwargs):
  280. self.short_size = short_size
  281. def __call__(self, data):
  282. img = data["image"]
  283. org_img_shape = img.shape
  284. h, w = img.shape[0:2]
  285. scale = self.short_size * 1.0 / min(h, w)
  286. h = int(h * scale + 0.5)
  287. w = int(w * scale + 0.5)
  288. if h % 32 != 0:
  289. h = h + (32 - h % 32)
  290. if w % 32 != 0:
  291. w = w + (32 - w % 32)
  292. img = cv2.resize(img, dsize=(w, h))
  293. new_img_shape = img.shape
  294. img_shape = np.array(org_img_shape + new_img_shape)
  295. data["shape"] = img_shape
  296. data["image"] = img
  297. return data