utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. # Copyright (c) <2015-Present> Tzutalin
  2. # Copyright (C) 2013 MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
  3. # William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  4. # associated documentation files (the "Software"), to deal in the Software without restriction, including without
  5. # limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
  6. # Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  7. # The above copyright notice and this permission notice shall be included in all copies or substantial portions of
  8. # the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
  9. # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  10. # SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  11. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  12. # THE SOFTWARE.
  13. import hashlib
  14. import os
  15. import re
  16. import sys
  17. from math import sqrt
  18. import cv2
  19. import numpy as np
  20. from PyQt5.QtCore import QRegExp, QT_VERSION_STR
  21. from PyQt5.QtGui import QIcon, QRegExpValidator, QColor
  22. from PyQt5.QtWidgets import QPushButton, QAction, QMenu
  23. from libs.ustr import ustr
  24. __dir__ = os.path.dirname(os.path.abspath(__file__)) # 获取本程序文件路径
  25. __iconpath__ = os.path.abspath(os.path.join(__dir__, '../resources/icons'))
  26. def newIcon(icon, iconSize=None):
  27. if iconSize is not None:
  28. return QIcon(QIcon(__iconpath__ + "/" + icon + ".png").pixmap(iconSize, iconSize))
  29. else:
  30. return QIcon(__iconpath__ + "/" + icon + ".png")
  31. def newButton(text, icon=None, slot=None):
  32. b = QPushButton(text)
  33. if icon is not None:
  34. b.setIcon(newIcon(icon))
  35. if slot is not None:
  36. b.clicked.connect(slot)
  37. return b
  38. def newAction(parent, text, slot=None, shortcut=None, icon=None,
  39. tip=None, checkable=False, enabled=True, iconSize=None):
  40. """Create a new action and assign callbacks, shortcuts, etc."""
  41. a = QAction(text, parent)
  42. if icon is not None:
  43. if iconSize is not None:
  44. a.setIcon(newIcon(icon, iconSize))
  45. else:
  46. a.setIcon(newIcon(icon))
  47. if shortcut is not None:
  48. if isinstance(shortcut, (list, tuple)):
  49. a.setShortcuts(shortcut)
  50. else:
  51. a.setShortcut(shortcut)
  52. if tip is not None:
  53. a.setToolTip(tip)
  54. a.setStatusTip(tip)
  55. if slot is not None:
  56. a.triggered.connect(slot)
  57. if checkable:
  58. a.setCheckable(True)
  59. a.setEnabled(enabled)
  60. return a
  61. def addActions(widget, actions):
  62. for action in actions:
  63. if action is None:
  64. widget.addSeparator()
  65. elif isinstance(action, QMenu):
  66. widget.addMenu(action)
  67. else:
  68. widget.addAction(action)
  69. def labelValidator():
  70. return QRegExpValidator(QRegExp(r'^[^ \t].+'), None)
  71. class struct(object):
  72. def __init__(self, **kwargs):
  73. self.__dict__.update(kwargs)
  74. def distance(p):
  75. return sqrt(p.x() * p.x() + p.y() * p.y())
  76. def fmtShortcut(text):
  77. mod, key = text.split('+', 1)
  78. return '<b>%s</b>+<b>%s</b>' % (mod, key)
  79. def generateColorByText(text):
  80. s = ustr(text)
  81. hashCode = int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16)
  82. r = int((hashCode / 255) % 255)
  83. g = int((hashCode / 65025) % 255)
  84. b = int((hashCode / 16581375) % 255)
  85. return QColor(r, g, b, 100)
  86. def have_qstring():
  87. '''p3/qt5 get rid of QString wrapper as py3 has native unicode str type'''
  88. return not (sys.version_info.major >= 3 or QT_VERSION_STR.startswith('5.'))
  89. def natural_sort(list, key=lambda s: s):
  90. """
  91. Sort the list into natural alphanumeric order.
  92. """
  93. def get_alphanum_key_func(key):
  94. convert = lambda text: int(text) if text.isdigit() else text
  95. return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))]
  96. sort_key = get_alphanum_key_func(key)
  97. list.sort(key=sort_key)
  98. def get_rotate_crop_image(img, points):
  99. # Use Green's theory to judge clockwise or counterclockwise
  100. # author: biyanhua
  101. d = 0.0
  102. for index in range(-1, 3):
  103. d += -0.5 * (points[index + 1][1] + points[index][1]) * (
  104. points[index + 1][0] - points[index][0])
  105. if d < 0: # counterclockwise
  106. tmp = np.array(points)
  107. points[1], points[3] = tmp[3], tmp[1]
  108. try:
  109. img_crop_width = int(
  110. max(
  111. np.linalg.norm(points[0] - points[1]),
  112. np.linalg.norm(points[2] - points[3])))
  113. img_crop_height = int(
  114. max(
  115. np.linalg.norm(points[0] - points[3]),
  116. np.linalg.norm(points[1] - points[2])))
  117. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  118. [img_crop_width, img_crop_height],
  119. [0, img_crop_height]])
  120. M = cv2.getPerspectiveTransform(points, pts_std)
  121. dst_img = cv2.warpPerspective(
  122. img,
  123. M, (img_crop_width, img_crop_height),
  124. borderMode=cv2.BORDER_REPLICATE,
  125. flags=cv2.INTER_CUBIC)
  126. dst_img_height, dst_img_width = dst_img.shape[0:2]
  127. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  128. dst_img = np.rot90(dst_img)
  129. return dst_img
  130. except Exception as e:
  131. print(e)
  132. def boxPad(box, imgShape, pad : int) -> np.array:
  133. """
  134. Pad a box with [pad] pixels on each side.
  135. """
  136. box = np.array(box, dtype=np.int32)
  137. box[0][0], box[0][1] = box[0][0] - pad, box[0][1] - pad
  138. box[1][0], box[1][1] = box[1][0] + pad, box[1][1] - pad
  139. box[2][0], box[2][1] = box[2][0] + pad, box[2][1] + pad
  140. box[3][0], box[3][1] = box[3][0] - pad, box[3][1] + pad
  141. h, w, _ = imgShape
  142. box[:,0] = np.clip(box[:,0], 0, w)
  143. box[:,1] = np.clip(box[:,1], 0, h)
  144. return box
  145. def expand_list(merged, html_list):
  146. '''
  147. Fill blanks according to merged cells
  148. '''
  149. sr, er, sc, ec = merged
  150. for i in range(sr, er):
  151. for j in range(sc, ec):
  152. html_list[i][j] = None
  153. html_list[sr][sc] = ''
  154. if ec - sc > 1:
  155. html_list[sr][sc] += " colspan={}".format(ec - sc)
  156. if er - sr > 1:
  157. html_list[sr][sc] += " rowspan={}".format(er - sr)
  158. return html_list
  159. def convert_token(html_list):
  160. '''
  161. Convert raw html to label format
  162. '''
  163. token_list = ["<tbody>"]
  164. # final html list:
  165. for row in html_list:
  166. token_list.append("<tr>")
  167. for col in row:
  168. if col == None:
  169. continue
  170. elif col == 'td':
  171. token_list.extend(["<td>", "</td>"])
  172. else:
  173. token_list.append("<td")
  174. if 'colspan' in col:
  175. _, n = col.split('colspan=')
  176. token_list.append(" colspan=\"{}\"".format(n[0]))
  177. if 'rowspan' in col:
  178. _, n = col.split('rowspan=')
  179. token_list.append(" rowspan=\"{}\"".format(n[0]))
  180. token_list.extend([">", "</td>"])
  181. token_list.append("</tr>")
  182. token_list.append("</tbody>")
  183. return token_list
  184. def rebuild_html_from_ppstructure_label(label_info):
  185. from html import escape
  186. html_code = label_info['html']['structure']['tokens'].copy()
  187. to_insert = [
  188. i for i, tag in enumerate(html_code) if tag in ('<td>', '>')
  189. ]
  190. for i, cell in zip(to_insert[::-1], label_info['html']['cells'][::-1]):
  191. if cell['tokens']:
  192. cell = [
  193. escape(token) if len(token) == 1 else token
  194. for token in cell['tokens']
  195. ]
  196. cell = ''.join(cell)
  197. html_code.insert(i + 1, cell)
  198. html_code = ''.join(html_code)
  199. html_code = '<html><body><table>{}</table></body></html>'.format(
  200. html_code)
  201. return html_code
  202. def stepsInfo(lang='en'):
  203. if lang == 'ch':
  204. msg = "1. 安装与运行:使用上述命令安装与运行程序。\n" \
  205. "2. 打开文件夹:在菜单栏点击 “文件” - 打开目录 选择待标记图片的文件夹.\n" \
  206. "3. 自动标注:点击 ”自动标注“,使用PPOCR超轻量模型对图片文件名前图片状态为 “X” 的图片进行自动标注。\n" \
  207. "4. 手动标注:点击 “矩形标注”(推荐直接在英文模式下点击键盘中的 “W”),用户可对当前图片中模型未检出的部分进行手动" \
  208. "绘制标记框。点击键盘P,则使用四点标注模式(或点击“编辑” - “四点标注”),用户依次点击4个点后,双击左键表示标注完成。\n" \
  209. "5. 标记框绘制完成后,用户点击 “确认”,检测框会先被预分配一个 “待识别” 标签。\n" \
  210. "6. 重新识别:将图片中的所有检测画绘制/调整完成后,点击 “重新识别”,PPOCR模型会对当前图片中的**所有检测框**重新识别。\n" \
  211. "7. 内容更改:双击识别结果,对不准确的识别结果进行手动更改。\n" \
  212. "8. 保存:点击 “保存”,图片状态切换为 “√”,跳转至下一张。\n" \
  213. "9. 删除:点击 “删除图像”,图片将会被删除至回收站。\n" \
  214. "10. 标注结果:关闭应用程序或切换文件路径后,手动保存过的标签将会被存放在所打开图片文件夹下的" \
  215. "*Label.txt*中。在菜单栏点击 “PaddleOCR” - 保存识别结果后,会将此类图片的识别训练数据保存在*crop_img*文件夹下," \
  216. "识别标签保存在*rec_gt.txt*中。\n"
  217. else:
  218. msg = "1. Build and launch using the instructions above.\n" \
  219. "2. Click 'Open Dir' in Menu/File to select the folder of the picture.\n" \
  220. "3. Click 'Auto recognition', use PPOCR model to automatically annotate images which marked with 'X' before the file name." \
  221. "4. Create Box:\n" \
  222. "4.1 Click 'Create RectBox' or press 'W' in English keyboard mode to draw a new rectangle detection box. Click and release left mouse to select a region to annotate the text area.\n" \
  223. "4.2 Press 'P' to enter four-point labeling mode which enables you to create any four-point shape by clicking four points with the left mouse button in succession and DOUBLE CLICK the left mouse as the signal of labeling completion.\n" \
  224. "5. After the marking frame is drawn, the user clicks 'OK', and the detection frame will be pre-assigned a TEMPORARY label.\n" \
  225. "6. Click re-Recognition, model will rewrite ALL recognition results in ALL detection box.\n" \
  226. "7. Double click the result in 'recognition result' list to manually change inaccurate recognition results.\n" \
  227. "8. Click 'Save', the image status will switch to '√',then the program automatically jump to the next.\n" \
  228. "9. Click 'Delete Image' and the image will be deleted to the recycle bin.\n" \
  229. "10. Labeling result: After closing the application or switching the file path, the manually saved label will be stored in *Label.txt* under the opened picture folder.\n" \
  230. " Click PaddleOCR-Save Recognition Results in the menu bar, the recognition training data of such pictures will be saved in the *crop_img* folder, and the recognition label will be saved in *rec_gt.txt*.\n"
  231. return msg
  232. def keysInfo(lang='en'):
  233. if lang == 'ch':
  234. msg = "快捷键\t\t\t说明\n" \
  235. "———————————————————————\n" \
  236. "Ctrl + shift + R\t\t对当前图片的所有标记重新识别\n" \
  237. "W\t\t\t新建矩形框\n" \
  238. "Q\t\t\t新建四点框\n" \
  239. "Ctrl + E\t\t编辑所选框标签\n" \
  240. "Ctrl + R\t\t重新识别所选标记\n" \
  241. "Ctrl + C\t\t复制并粘贴选中的标记框\n" \
  242. "Ctrl + 鼠标左键\t\t多选标记框\n" \
  243. "Backspace\t\t删除所选框\n" \
  244. "Ctrl + V\t\t确认本张图片标记\n" \
  245. "Ctrl + Shift + d\t删除本张图片\n" \
  246. "D\t\t\t下一张图片\n" \
  247. "A\t\t\t上一张图片\n" \
  248. "Ctrl++\t\t\t缩小\n" \
  249. "Ctrl--\t\t\t放大\n" \
  250. "↑→↓←\t\t\t移动标记框\n" \
  251. "———————————————————————\n" \
  252. "注:Mac用户Command键替换上述Ctrl键"
  253. else:
  254. msg = "Shortcut Keys\t\tDescription\n" \
  255. "———————————————————————\n" \
  256. "Ctrl + shift + R\t\tRe-recognize all the labels\n" \
  257. "\t\t\tof the current image\n" \
  258. "\n" \
  259. "W\t\t\tCreate a rect box\n" \
  260. "Q\t\t\tCreate a four-points box\n" \
  261. "Ctrl + E\t\tEdit label of the selected box\n" \
  262. "Ctrl + R\t\tRe-recognize the selected box\n" \
  263. "Ctrl + C\t\tCopy and paste the selected\n" \
  264. "\t\t\tbox\n" \
  265. "\n" \
  266. "Ctrl + Left Mouse\tMulti select the label\n" \
  267. "Button\t\t\tbox\n" \
  268. "\n" \
  269. "Backspace\t\tDelete the selected box\n" \
  270. "Ctrl + V\t\tCheck image\n" \
  271. "Ctrl + Shift + d\tDelete image\n" \
  272. "D\t\t\tNext image\n" \
  273. "A\t\t\tPrevious image\n" \
  274. "Ctrl++\t\t\tZoom in\n" \
  275. "Ctrl--\t\t\tZoom out\n" \
  276. "↑→↓←\t\t\tMove selected box" \
  277. "———————————————————————\n" \
  278. "Notice:For Mac users, use the 'Command' key instead of the 'Ctrl' key"
  279. return msg