module_rename_pic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. from UI.rename_pic import Ui_Form as rename_pic_Ui_Form
  2. from PySide6.QtWidgets import *
  3. from PySide6.QtCore import *
  4. # from collections import defaultdict
  5. import os
  6. import log
  7. from PIL import Image, ImageDraw, ImageFont
  8. import time
  9. import settings
  10. # from pyzbar.pyzbar import decode
  11. import shutil
  12. from cv2 import cvtColor, COLOR_RGB2BGR
  13. # cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR)
  14. import numpy as np
  15. from cv2.wechat_qrcode import WeChatQRCode
  16. from module.module_online_data import GetOnlineData
  17. # pip install opencv-python -i https://pypi.douban.com/simple
  18. # pip install opencv-contrib-python -i https://pypi.douban.com/simple
  19. class Picture:
  20. def __init__(self, in_path):
  21. self.im = Image.open(in_path)
  22. self.x, self.y = self.im.size
  23. # print(self.x, self.y)
  24. def save_img(self, outpath, quality=90):
  25. # self.im = self.im.convert("RGB")
  26. self.im.save(outpath, quality=quality)
  27. def resize(self, width):
  28. re_x = int(width)
  29. re_y = int(self.y * re_x / self.x)
  30. self.im = self.im.resize((re_x, re_y), Image.Resampling.LANCZOS)
  31. self.x, self.y = self.im.size
  32. def resize_regular(self, width, high):
  33. self.im = self.im.resize((width, high), Image.Resampling.LANCZOS)
  34. def corp_square(self):
  35. if self.y < self.x:
  36. return
  37. self.im = self.im.crop((0, int((self.y - self.x) / 2), self.x, self.y - int((self.y - self.x) / 2)))
  38. class RenamePic(QWidget, rename_pic_Ui_Form):
  39. progress_sign = Signal(dict)
  40. info_sign = Signal(str)
  41. text_show = Signal(str)
  42. def __init__(self, windows=None):
  43. super().__init__()
  44. # 加载默认配置
  45. self.setupUi(self)
  46. # 0禁用 1进行中 2已结束
  47. self.state = 2
  48. self.init()
  49. self.pic_dir = ""
  50. self.setFixedSize(self.width(), self.height())
  51. self.set_state(2)
  52. self.show()
  53. QTimer.singleShot(500, self.check_login)
  54. def check_login(self, *args):
  55. if not settings.IsLogin:
  56. a = QMessageBox.question(self, '确认', '请先登录',
  57. QMessageBox.Yes)
  58. self.close()
  59. def init(self):
  60. self.text_show.connect(self.append_text_to_browser)
  61. self.label_3.mousePressEvent = self.select_pic_dir
  62. self.label_4.setText("")
  63. # self.label_6.setText(self.get_len_text(self.to_deal_excel_dir, 50))
  64. self.pushButton.clicked.connect(self.run)
  65. def create_folder(self, path):
  66. if not os.path.exists(path):
  67. os.makedirs(path)
  68. def get_len_text(self, text, max_len: int):
  69. if len(text) > max_len:
  70. text = text[:int(max_len / 4)] + "..." + text[-1 * int(max_len * 3 / 4):]
  71. return text
  72. def select_pic_dir(self, *args):
  73. pic_dir = QFileDialog.getExistingDirectory(None, "选取文件夹", "")
  74. if not pic_dir:
  75. self.label_4.setText("")
  76. return
  77. self.pic_dir = pic_dir
  78. self.label_4.setText(pic_dir)
  79. def check_path(self, _path):
  80. if not os.path.exists(_path):
  81. os.mkdir(_path)
  82. return True
  83. def set_state(self, state_value: int):
  84. # 0禁用 1进行中 2已结束
  85. if state_value not in [0, 1, 2]:
  86. return
  87. self.state = state_value
  88. if self.state == 0:
  89. self.progressBar.hide()
  90. self.pushButton.setEnabled(False)
  91. if self.state == 1:
  92. self.progressBar.show()
  93. self.progressBar.setValue(0)
  94. self.textBrowser_2.show()
  95. self.pushButton.setEnabled(False)
  96. self.textBrowser_2.clear()
  97. if self.state == 2:
  98. self.progressBar.hide()
  99. self.pushButton.setEnabled(True)
  100. def run(self):
  101. # 基础检查
  102. if not settings.IsLogin:
  103. a = QMessageBox.question(self, '确认', '请先登录',
  104. QMessageBox.Yes)
  105. return
  106. self.set_state(1)
  107. if not self.pic_dir:
  108. self.text_show.emit("请选择图片文件夹")
  109. self.set_state(2)
  110. return
  111. if self.comboBox.currentText() == "请选择":
  112. self.text_show.emit("请选择是否将货号添加到图片中")
  113. self.set_state(2)
  114. return
  115. total = 0
  116. _Type = ['.png', '.PNG', '.jpg', '.JPG', '.gif', '.GIF', '.jpeg', '.JPEG']
  117. for image_file in os.listdir(self.pic_dir):
  118. path = "{}\{}".format(self.pic_dir, image_file)
  119. if os.path.isfile(path):
  120. if os.path.splitext(image_file)[1] in _Type:
  121. total += 1
  122. if total == 0:
  123. self.text_show.emit("当前文件夹下没有图片")
  124. self.set_state(2)
  125. return
  126. is_add_text = False
  127. if self.comboBox.currentText() == "添加":
  128. is_add_text = True
  129. self.run_deal(total=total, is_add_text=is_add_text)
  130. self.set_state(2)
  131. def send_info(self, data):
  132. if data["_type"] == "show_p":
  133. self.progressBar.setValue(data["data"])
  134. if data["_type"] == "text":
  135. self.textBrowser_2.append(data["data"])
  136. def run_deal(self, total, is_add_text=False):
  137. # 输出目录
  138. out_put_path = "{}\out_put_{}".format(os.path.split(self.pic_dir)[0], int(time.time()))
  139. # 无法识别的目录
  140. error_path = "{}\识别失败".format(out_put_path)
  141. # 识别成功的目录
  142. success_path = "{}\识别成功".format(out_put_path)
  143. self.check_path(out_put_path)
  144. self.check_path(error_path)
  145. self.check_path(success_path)
  146. error_list = []
  147. _Type = ['.png', '.PNG', '.jpg', '.JPG', '.gif', '.GIF', '.jpeg', '.JPEG']
  148. last_code = None
  149. do_n = 0
  150. for image_file in os.listdir(self.pic_dir):
  151. if os.path.splitext(image_file)[1] in _Type:
  152. # 获取当前路径的文件夹名称
  153. file_path = "{}/{}".format(self.pic_dir, image_file)
  154. self.send_info({"_type": "text",
  155. "data": "{}图片解析".format(image_file)})
  156. code = self.get_code(file_path)
  157. if code:
  158. if "_" in code:
  159. goods_number = code.split("_")[0]
  160. numbers_list = [goods_number]
  161. r_data = GetOnlineData().get_goods_art_no_info(numbers_list=numbers_list)
  162. if goods_number in r_data:
  163. code = r_data[goods_number]["商品货号"]
  164. else:
  165. code = None
  166. self.send_info({"_type": "text",
  167. "data": "{}查询不到商品".format(goods_number)})
  168. if code:
  169. # 获取到二维码内容,说明是二维码图片,则不做处理
  170. last_code = code
  171. continue
  172. else:
  173. # 上个二维码没有解析成功
  174. if not last_code:
  175. error_list.append(image_file)
  176. self.send_info({"_type": "text",
  177. "data": "{}无法识别".format(image_file)})
  178. shutil.copyfile(file_path, "{}\{}".format(error_path, image_file))
  179. #
  180. if last_code:
  181. print("{}--------".format(last_code))
  182. # 目标文件路径
  183. _file_name = "{}{}".format(last_code, os.path.splitext(image_file)[1])
  184. dst_file = "{}/{}".format(success_path, _file_name)
  185. if os.path.exists(dst_file):
  186. self.send_info({"_type": "text",
  187. "data": "{}图片已存在".format(image_file)})
  188. last_code = None
  189. continue
  190. shutil.copy(file_path, dst_file) # 复制文件
  191. pic = Picture(dst_file)
  192. pic.resize(width=800)
  193. pic.corp_square() # 居中剪裁
  194. if is_add_text:
  195. draw = ImageDraw.Draw(pic.im)
  196. font_style_1 = ImageFont.truetype(r"ttf\simfang.ttf", 40, encoding="utf-8")
  197. draw.text((0, 0), last_code, 0, font=font_style_1)
  198. pic.save_img(dst_file)
  199. # 处理成功了,清空上个记录
  200. last_code = None
  201. do_n += 1
  202. self.send_info({"_type": "show_p",
  203. "data": int(do_n / total * 100)})
  204. if error_list:
  205. self.send_info({"_type": "text",
  206. "data": "以下图片无法解析,请自行处理"})
  207. self.send_info({"_type": "text",
  208. "data": "{}".format(error_list)})
  209. os.startfile(out_put_path)
  210. def append_text_to_browser(self, text):
  211. self.textBrowser_2.append(text)
  212. def create_folder(self, path):
  213. if not os.path.exists(path):
  214. os.makedirs(path)
  215. return False
  216. def get_code(self, file_path):
  217. pic = Picture(file_path)
  218. pic.resize(width=1000)
  219. im = pic.im
  220. img = cvtColor(np.asarray(im), COLOR_RGB2BGR)
  221. # path = r"D:\MyDocuments\PythonCode\MyPython\red_dragonfly\deal_pics\rename_by_qrcode\opencv_3rdparty-wechat_qrcode"
  222. detector = WeChatQRCode(detector_prototxt_path="qr_mode/detect.prototxt",
  223. detector_caffe_model_path="qr_mode/detect.caffemodel",
  224. super_resolution_prototxt_path="qr_mode/sr.prototxt",
  225. super_resolution_caffe_model_path="qr_mode/sr.caffemodel")
  226. res, points = detector.detectAndDecode(img)
  227. if res:
  228. return res[0]
  229. return None
  230. def deal_pic_resize(self, file_path, target_size, times=0, ):
  231. file_size = int(os.path.getsize(file_path) / 1024)
  232. if file_size < target_size:
  233. return
  234. times += 1
  235. if times > 2:
  236. print(file_path, "压缩次数", times)
  237. k = 0.9
  238. # if file_size > target_size * 5:
  239. # k = 0.7
  240. pic = Picture(file_path)
  241. w = int(pic.x * k)
  242. pic.resize(w)
  243. pic.save_img(file_path)
  244. return self.deal_pic_resize(file_path, target_size, times)