utils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. from math import sqrt
  14. from libs.ustr import ustr
  15. import hashlib
  16. import re
  17. import sys
  18. import cv2
  19. import numpy as np
  20. try:
  21. from PyQt5.QtGui import *
  22. from PyQt5.QtCore import *
  23. from PyQt5.QtWidgets import *
  24. except ImportError:
  25. from PyQt4.QtGui import *
  26. from PyQt4.QtCore import *
  27. def newIcon(icon, iconSize=None):
  28. if iconSize is not None:
  29. return QIcon(QIcon(':/' + icon).pixmap(iconSize,iconSize))
  30. else:
  31. return QIcon(':/' + icon)
  32. def newButton(text, icon=None, slot=None):
  33. b = QPushButton(text)
  34. if icon is not None:
  35. b.setIcon(newIcon(icon))
  36. if slot is not None:
  37. b.clicked.connect(slot)
  38. return b
  39. def newAction(parent, text, slot=None, shortcut=None, icon=None,
  40. tip=None, checkable=False, enabled=True, iconSize=None):
  41. """Create a new action and assign callbacks, shortcuts, etc."""
  42. a = QAction(text, parent)
  43. if icon is not None:
  44. if iconSize is not None:
  45. a.setIcon(newIcon(icon, iconSize))
  46. else:
  47. a.setIcon(newIcon(icon))
  48. if shortcut is not None:
  49. if isinstance(shortcut, (list, tuple)):
  50. a.setShortcuts(shortcut)
  51. else:
  52. a.setShortcut(shortcut)
  53. if tip is not None:
  54. a.setToolTip(tip)
  55. a.setStatusTip(tip)
  56. if slot is not None:
  57. a.triggered.connect(slot)
  58. if checkable:
  59. a.setCheckable(True)
  60. a.setEnabled(enabled)
  61. return a
  62. def addActions(widget, actions):
  63. for action in actions:
  64. if action is None:
  65. widget.addSeparator()
  66. elif isinstance(action, QMenu):
  67. widget.addMenu(action)
  68. else:
  69. widget.addAction(action)
  70. def labelValidator():
  71. return QRegExpValidator(QRegExp(r'^[^ \t].+'), None)
  72. class struct(object):
  73. def __init__(self, **kwargs):
  74. self.__dict__.update(kwargs)
  75. def distance(p):
  76. return sqrt(p.x() * p.x() + p.y() * p.y())
  77. def fmtShortcut(text):
  78. mod, key = text.split('+', 1)
  79. return '<b>%s</b>+<b>%s</b>' % (mod, key)
  80. def generateColorByText(text):
  81. s = ustr(text)
  82. hashCode = int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16)
  83. r = int((hashCode / 255) % 255)
  84. g = int((hashCode / 65025) % 255)
  85. b = int((hashCode / 16581375) % 255)
  86. return QColor(r, g, b, 100)
  87. def have_qstring():
  88. '''p3/qt5 get rid of QString wrapper as py3 has native unicode str type'''
  89. return not (sys.version_info.major >= 3 or QT_VERSION_STR.startswith('5.'))
  90. def util_qt_strlistclass():
  91. return QStringList if have_qstring() else list
  92. def natural_sort(list, key=lambda s:s):
  93. """
  94. Sort the list into natural alphanumeric order.
  95. """
  96. def get_alphanum_key_func(key):
  97. convert = lambda text: int(text) if text.isdigit() else text
  98. return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))]
  99. sort_key = get_alphanum_key_func(key)
  100. list.sort(key=sort_key)
  101. def get_rotate_crop_image(img, points):
  102. try:
  103. img_crop_width = int(
  104. max(
  105. np.linalg.norm(points[0] - points[1]),
  106. np.linalg.norm(points[2] - points[3])))
  107. img_crop_height = int(
  108. max(
  109. np.linalg.norm(points[0] - points[3]),
  110. np.linalg.norm(points[1] - points[2])))
  111. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  112. [img_crop_width, img_crop_height],
  113. [0, img_crop_height]])
  114. M = cv2.getPerspectiveTransform(points, pts_std)
  115. dst_img = cv2.warpPerspective(
  116. img,
  117. M, (img_crop_width, img_crop_height),
  118. borderMode=cv2.BORDER_REPLICATE,
  119. flags=cv2.INTER_CUBIC)
  120. dst_img_height, dst_img_width = dst_img.shape[0:2]
  121. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  122. dst_img = np.rot90(dst_img)
  123. return dst_img
  124. except Exception as e:
  125. print(e)
  126. def stepsInfo(lang='en'):
  127. if lang == 'ch':
  128. msg = "1. 安装与运行:使用上述命令安装与运行程序。\n" \
  129. "2. 打开文件夹:在菜单栏点击 “文件” - 打开目录 选择待标记图片的文件夹.\n"\
  130. "3. 自动标注:点击 ”自动标注“,使用PPOCR超轻量模型对图片文件名前图片状态为 “X” 的图片进行自动标注。\n" \
  131. "4. 手动标注:点击 “矩形标注”(推荐直接在英文模式下点击键盘中的 “W”),用户可对当前图片中模型未检出的部分进行手动" \
  132. "绘制标记框。点击键盘P,则使用四点标注模式(或点击“编辑” - “四点标注”),用户依次点击4个点后,双击左键表示标注完成。\n" \
  133. "5. 标记框绘制完成后,用户点击 “确认”,检测框会先被预分配一个 “待识别” 标签。\n" \
  134. "6. 重新识别:将图片中的所有检测画绘制/调整完成后,点击 “重新识别”,PPOCR模型会对当前图片中的**所有检测框**重新识别。\n" \
  135. "7. 内容更改:双击识别结果,对不准确的识别结果进行手动更改。\n" \
  136. "8. 保存:点击 “保存”,图片状态切换为 “√”,跳转至下一张。\n" \
  137. "9. 删除:点击 “删除图像”,图片将会被删除至回收站。\n" \
  138. "10. 标注结果:关闭应用程序或切换文件路径后,手动保存过的标签将会被存放在所打开图片文件夹下的" \
  139. "*Label.txt*中。在菜单栏点击 “PaddleOCR” - 保存识别结果后,会将此类图片的识别训练数据保存在*crop_img*文件夹下," \
  140. "识别标签保存在*rec_gt.txt*中。\n"
  141. else:
  142. msg = "1. Build and launch using the instructions above.\n" \
  143. "2. Click 'Open Dir' in Menu/File to select the folder of the picture.\n"\
  144. "3. Click 'Auto recognition', use PPOCR model to automatically annotate images which marked with 'X' before the file name."\
  145. "4. Create Box:\n"\
  146. "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"\
  147. "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"\
  148. "5. After the marking frame is drawn, the user clicks 'OK', and the detection frame will be pre-assigned a TEMPORARY label.\n"\
  149. "6. Click re-Recognition, model will rewrite ALL recognition results in ALL detection box.\n"\
  150. "7. Double click the result in 'recognition result' list to manually change inaccurate recognition results.\n"\
  151. "8. Click 'Save', the image status will switch to '√',then the program automatically jump to the next.\n"\
  152. "9. Click 'Delete Image' and the image will be deleted to the recycle bin.\n"\
  153. "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"\
  154. " 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"
  155. return msg