deal_one_image.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import copy
  2. import os.path
  3. from .other.module_online_data import GetOnlineData
  4. import time
  5. from .other.log import MyLogger
  6. import os
  7. from .remove_bg_pixian import RemoveBgPiXian
  8. from PIL import Image
  9. from .other.pic import Picture
  10. from .other.remove_bg_ali import RemoveBgALi
  11. import cv2
  12. import numpy as np
  13. from middleware import UnicornException
  14. import math
  15. def disposeWH(image: Image, base_size=1024):
  16. width, height = image.size
  17. scale_width = int(width)
  18. scale_height = int(height)
  19. scale_rate = scale_width / scale_height
  20. if scale_width > base_size:
  21. scale_width = base_size
  22. scale_height = int(math.floor(scale_width / scale_rate))
  23. if scale_height > base_size:
  24. scale_height = base_size
  25. scale_width = int(math.floor(scale_height * scale_rate))
  26. return scale_width, scale_height
  27. class Base(object):
  28. def __init__(self, image_data, lock, windows, num, token):
  29. self.lock = lock
  30. self.image_data = image_data
  31. self.num = num
  32. self.windows = windows
  33. self.get_online_data = GetOnlineData(token)
  34. self.file_path = image_data["file_path"]
  35. self.file_name = image_data["file_name"]
  36. self.file = os.path.split(self.file_path)[1]
  37. self.is_once_data = {}
  38. self.logger = MyLogger().logger
  39. def add_log(self, text, _type="info"):
  40. self.logger.info(
  41. "第{}个,图片名称:{},内容:{}".format(self.num, self.file, text)
  42. )
  43. def show_image_info(self, data):
  44. data["file_path"] = self.file_path
  45. with self.lock:
  46. data = {
  47. "_type": "show_image_item_info",
  48. "data": data,
  49. }
  50. # self.windows.signal_data.emit(data)
  51. def send_info(
  52. self,
  53. text="",
  54. is_success=None,
  55. _type="show_text_browser",
  56. need_point_return=False,
  57. ):
  58. with self.lock:
  59. if is_success is not None:
  60. if is_success:
  61. processing_failed = 0
  62. processing_successfully = 1
  63. else:
  64. processing_failed = 1
  65. processing_successfully = 0
  66. # 分数返回
  67. if need_point_return:
  68. # 分数返回
  69. if self.is_once("add_point"):
  70. print(
  71. "第{}个,图片名称:{},内容:{}".format(
  72. self.num, self.file, "扣分返回"
  73. )
  74. )
  75. self.dispose_point(_type="add")
  76. self.refresh_times(cumulative_frequency_times_change=-1)
  77. pass
  78. # self.windows.signal_data.emit({"_type": "schedule",
  79. # "data": {"processing_failed": processing_failed,
  80. # "processing_successfully": processing_successfully,
  81. # }})
  82. if text:
  83. data = {
  84. "_type": "show_text_browser",
  85. "data": text,
  86. }
  87. # self.windows.signal_data.emit(data)
  88. def check_path(self, _path):
  89. if not os.path.exists(_path):
  90. os.mkdir(_path)
  91. return True
  92. def is_once(self, key):
  93. if key not in self.is_once_data:
  94. self.is_once_data[key] = 0
  95. return True
  96. return False
  97. def refresh_times(self, cumulative_frequency_times_change=0):
  98. data = {
  99. "_type": "refresh_times",
  100. "data": {
  101. "cumulative_frequency_times_change": cumulative_frequency_times_change
  102. },
  103. }
  104. # self.windows.signal_data.emit(data)
  105. pass
  106. def dispose_point(self, _type):
  107. n = 3
  108. while n:
  109. n -= 1
  110. try:
  111. _r = self.get_online_data.dispose_point(_type)
  112. balance = _r["data"]["balance"]
  113. return True
  114. except:
  115. time.sleep(0.5)
  116. continue
  117. return False
  118. class DealOneImage(Base):
  119. def __init__(self, image_data, lock, windows, num, token):
  120. super().__init__(image_data, lock, windows, num, token)
  121. self.r_pixian = RemoveBgPiXian()
  122. self.windows = windows
  123. def run(self, image_data, upload_pic_dict):
  124. self.file_path = image_data["file_path"]
  125. self.file = os.path.split(self.file_path)[1]
  126. self.root_path = image_data["root_path"]
  127. self.file_name = image_data["file_name"]
  128. cut_status = False
  129. success_path = ""
  130. # 直接调用抠图
  131. # 1、增加获取key,2、key需要加密、3、429报错 重试再来拿一个KEY
  132. self.add_log("开始处理")
  133. remaining_times = self.get_online_data.get_cutout_image_times().get("balance")
  134. print("remaining_times", remaining_times)
  135. if remaining_times <= 0:
  136. raise UnicornException("次数不足,处理失败")
  137. # 检查图片上传是否有结束
  138. n = 60
  139. if self.file_path not in upload_pic_dict:
  140. # 不扣图
  141. raise UnicornException("处理失败")
  142. s = time.time()
  143. image_deal_info = upload_pic_dict[self.file_path]["image_deal_info"]
  144. original_im = upload_pic_dict[self.file_path]["_im"]
  145. self.add_log("抠图中")
  146. # 抠图
  147. out_root_path = "{}/已扣图".format(self.root_path)
  148. self.check_path(out_root_path)
  149. try:
  150. balance = self.get_online_data.get_cutout_image_times().get("balance")
  151. self.add_log("查询balance:{}成功".format(balance))
  152. if balance <= 0:
  153. self.add_log("次数不足,处理失败")
  154. raise UnicornException("次数不足,处理失败")
  155. except:
  156. self.add_log("查询balance失败")
  157. raise UnicornException("查询balance失败")
  158. n = 0
  159. second_cut_image = self.runPiXian(n, original_im=original_im)
  160. if second_cut_image is None:
  161. raise UnicornException("抠图失败")
  162. try:
  163. out_path = "{}/{}.png".format(out_root_path, self.file_name)
  164. if image_deal_info["二次抠图是否缩放"]:
  165. self.add_log(text="图片尺寸进行还原")
  166. original_im = image_deal_info["抠图扩边后PIL对象"]
  167. second_cut_image = self.picture_resize_to_original(
  168. second_cut_image, original_im
  169. )
  170. # 创建空白图片并粘贴回去
  171. _img_im = Image.new(
  172. mode="RGBA", size=image_deal_info["原始图片大小"], color=(0, 0, 0, 0)
  173. )
  174. _img_im.paste(
  175. second_cut_image,
  176. box=(
  177. image_deal_info["抠图扩边后位置"][0],
  178. image_deal_info["抠图扩边后位置"][1],
  179. ),
  180. )
  181. if self.windows.output_type == 1:
  182. print("处理白底", "ssssss")
  183. background = Image.new("RGBA", _img_im.size, (255, 255, 255, 255))
  184. _img_im = Image.alpha_composite(background, _img_im)
  185. resize_width, resize_height = disposeWH(_img_im.convert("RGB"), 1024)
  186. _img_im = _img_im.resize((resize_width, resize_height))
  187. new_bg = Image.new("RGB", (1024, 1024), (255, 255, 255))
  188. _img_im = _img_im.convert("RGB").copy()
  189. width, height = _img_im.size
  190. offset = ((1024 - width) // 2, (1024 - height) // 2)
  191. new_bg.paste(_img_im, offset)
  192. _img_im = new_bg.copy()
  193. cut_status = True
  194. success_path = out_path
  195. _img_im.save(out_path)
  196. except BaseException as e:
  197. text = "{} 图片处理错误,代码44".format(e)
  198. self.add_log(text)
  199. self.send_info(text=text, is_success=False, need_point_return=True)
  200. cut_status = False
  201. self.add_log(text="本张耗时:{}".format(time.time() - s))
  202. self.send_info(text="抠图已完成", is_success=True)
  203. image_data["status"] = cut_status
  204. image_data["success_path"] = success_path
  205. return image_data
  206. def runPiXian(self, num, original_im):
  207. """执行pixian抠图"""
  208. num += 1
  209. data = self.get_online_data.get_key_secret()
  210. key = (data["api_info"]["api_key"], data["api_info"]["api_serect"])
  211. self.add_log("查询key成功")
  212. if not key:
  213. raise UnicornException("处理失败,请联系管理员")
  214. if self.is_once("sub_point"):
  215. # 调用扣分
  216. self.refresh_times(cumulative_frequency_times_change=1)
  217. f = self.dispose_point(_type="sub")
  218. if not f:
  219. self.add_log(text="多次获取调用余额扣减失败")
  220. raise UnicornException("多次获取调用余额扣减失败")
  221. pixian_cutout_data = self.r_pixian.run_by_image_im(original_im, key)
  222. if pixian_cutout_data["status_code"] == 200:
  223. second_cut_image = pixian_cutout_data["im"]
  224. self.add_log(text="调用抠图完成")
  225. return second_cut_image
  226. elif pixian_cutout_data["status_code"] == 402:
  227. if num >= 2:
  228. self.cutoutFail(pixian_cutout_data)
  229. raise UnicornException("多次获取调用余额扣减失败")
  230. self.add_log(
  231. text="抠图失败:{},延迟6秒".format(pixian_cutout_data["status_code"])
  232. )
  233. time.sleep(6)
  234. self.runPiXian(num, original_im=original_im)
  235. elif pixian_cutout_data["status_code"] == 429:
  236. if num >= 2:
  237. self.cutoutFail(pixian_cutout_data)
  238. return None
  239. self.add_log(
  240. text="抠图失败:{},延迟10秒".format(pixian_cutout_data["status_code"])
  241. )
  242. time.sleep(10)
  243. self.runPiXian(num, original_im=original_im)
  244. else:
  245. _data = {
  246. "text": "出错/超时",
  247. "info": "抠图异常",
  248. }
  249. self.show_image_info(_data)
  250. self.get_online_data.dispose_point("add")
  251. if "message" in pixian_cutout_data:
  252. text = "抠图异常,code:{},message:{}".format(
  253. pixian_cutout_data["status_code"], pixian_cutout_data["message"]
  254. )
  255. else:
  256. text = "抠图异常,code:{}".format(pixian_cutout_data["status_code"])
  257. self.add_log(text)
  258. return None
  259. # if self.windows.output_type == 1:
  260. # resize_width, resize_height = disposeWH(
  261. # second_cut_image.convert("RGB"), 1024
  262. # )
  263. # second_cut_image = second_cut_image.resize((resize_width, resize_height))
  264. # new_bg = Image.new("RGB", (1024, 1024), (255, 255, 255))
  265. # second_cut_image = second_cut_image.convert("RGB").copy()
  266. # width, height = second_cut_image.size
  267. # offset = ((1024 - width) // 2, (1024 - height) // 2)
  268. # new_bg.paste(second_cut_image, offset)
  269. # second_cut_image = new_bg.copy()
  270. return second_cut_image
  271. def cutoutFail(self, pixian_cutout_data):
  272. """处理失败"""
  273. _data = {
  274. "text": "出错/超时",
  275. "info": "多次抠图失败:{}".format(pixian_cutout_data["status_code"]),
  276. }
  277. self.show_image_info(_data)
  278. self.add_log(text="多次抠图失败:{}".format(pixian_cutout_data["status_code"]))
  279. self.send_info(
  280. text="处理失败,请联系管理员",
  281. is_success=False,
  282. need_point_return=True,
  283. )
  284. def picture_resize_to_original(self, _img, original_im):
  285. """
  286. Parameters
  287. ----------
  288. _img 需要还原的PIL对象
  289. original_im 原图对象
  290. Returns
  291. -------
  292. """
  293. # 将抠图结果转成mask
  294. # 将抠图结果放大到原始图大小
  295. _img = _img.resize(original_im.size)
  296. new_big_mask = Image.new("RGB", _img.size, (0, 0, 0))
  297. white = Image.new("RGB", _img.size, (255, 255, 255))
  298. new_big_mask.paste(white, mask=_img.split()[3])
  299. # ---------制作选区缩小的mask
  300. mask = cv2.cvtColor(
  301. np.asarray(new_big_mask), cv2.COLOR_BGR2GRAY
  302. ) # 将PIL 格式转换为 CV对象
  303. mask[mask != 255] = 0
  304. # 黑白反转
  305. # mask = 255 - mask
  306. # 选区缩小10
  307. kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
  308. erode_im = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)
  309. # -------再进行抠图处理
  310. mask = Image.fromarray(
  311. cv2.cvtColor(erode_im, cv2.COLOR_GRAY2RGBA)
  312. ) # CV 对象转 PIL
  313. transparent_im = Image.new("RGBA", original_im.size, (0, 0, 0, 0))
  314. transparent_im.paste(original_im, (0, 0), mask.convert("L"))
  315. # 上述抠图结果进行拼接
  316. _img.paste(transparent_im, (0, 0), transparent_im)
  317. return _img
  318. class DealOneImageBeforehand(Base):
  319. def __init__(self, image_data, lock, windows, num, token):
  320. super().__init__(image_data, lock, windows, num, token)
  321. self.r_ali = RemoveBgALi()
  322. def run(self, upload_pic_dict):
  323. # 增加阿里调用报错的重试机制
  324. image_deal_info = {}
  325. try:
  326. cut_image, image_deal_info = self.get_image_cut()
  327. except BaseException as e:
  328. raise UnicornException("上传出错")
  329. upload_pic_dict[self.file_path] = {
  330. "image_deal_info": image_deal_info,
  331. "_im": cut_image,
  332. }
  333. return upload_pic_dict
  334. def get_image_cut(self):
  335. original_pic = Picture(self.file_path)
  336. original_pic.im = self.get_image_orientation(original_pic.im)
  337. original_pic.x, original_pic.y = original_pic.im.size
  338. original_pic.im = original_pic.im.convert("RGB")
  339. image_deal_info = {}
  340. image_deal_info["原始图片大小"] = (original_pic.x, original_pic.y)
  341. if original_pic.x * original_pic.y < 1000000:
  342. cut_image = original_pic.im
  343. image_deal_info["抠图扩边后图片大小"] = cut_image.size
  344. image_deal_info["二次抠图是否缩放"] = False
  345. image_deal_info["抠图扩边后位置"] = (0, 0, original_pic.x, original_pic.y)
  346. else:
  347. self.add_log("开始预抠图处理")
  348. cut_image = self.r_ali.get_image_cut(
  349. file_path=None, out_file_path=None, original_im=original_pic.im
  350. )
  351. self.add_log("预抠图处理结束")
  352. x1, y1, x2, y2 = cut_image.getbbox()
  353. image_deal_info["鞋子原始位置"] = (x1, y1, x2, y2)
  354. o_w, o_h = cut_image.size
  355. image_deal_info["鞋子原始抠图后大小"] = (o_w, o_h)
  356. # 扩边处理
  357. _w, _h = x2 - x1, y2 - y1
  358. out_px = 0.025
  359. _w, _h = int(out_px * _w), int(out_px * _h)
  360. n_x1, n_y1, n_x2, n_y2 = x1 - _w, y1 - _h, x2 + _w, y2 + _h
  361. if n_x1 < 0:
  362. n_x1 = 0
  363. if n_y1 < 0:
  364. n_y1 = 0
  365. if n_x2 > o_w:
  366. n_x2 = o_w
  367. if n_y2 > o_h:
  368. n_y2 = o_h
  369. image_deal_info["抠图扩边后位置"] = (n_x1, n_y1, n_x2, n_y2)
  370. cut_image = original_pic.im.crop(image_deal_info["抠图扩边后位置"])
  371. image_deal_info["抠图扩边后图片大小"] = cut_image.size
  372. x, y = image_deal_info["抠图扩边后图片大小"]
  373. # max_size = 32000000
  374. max_size = 12000000
  375. if x * y > max_size:
  376. r = max_size / (x * y)
  377. size = (int(x * r), int(y * r))
  378. self.add_log(
  379. text="图片进行压缩,压缩前:{},压缩后:{}".format(
  380. image_deal_info["抠图扩边后图片大小"], size
  381. )
  382. )
  383. image_deal_info["抠图扩边后PIL对象"] = copy.deepcopy(cut_image)
  384. cut_image = cut_image.resize(size=size)
  385. # print(cut_image.size)
  386. # print(image_deal_info["抠图扩边后PIL对象"].size)
  387. image_deal_info["二次抠图是否缩放"] = True
  388. else:
  389. image_deal_info["二次抠图是否缩放"] = False
  390. return cut_image, image_deal_info
  391. def get_image_cut_noraml(self, image_data):
  392. """普通模式抠图"""
  393. self.file_path = image_data["file_path"]
  394. self.file = os.path.split(self.file_path)[1]
  395. self.root_path = image_data["root_path"]
  396. self.file_name = image_data["file_name"]
  397. original_pic = Picture(self.file_path)
  398. original_pic.im = self.get_image_orientation(original_pic.im)
  399. original_pic.x, original_pic.y = original_pic.im.size
  400. original_pic.im = original_pic.im.convert("RGB")
  401. image_deal_info = {}
  402. image_deal_info["原始图片大小"] = (original_pic.x, original_pic.y)
  403. self.add_log("开始预抠图处理")
  404. remaining_times = self.get_online_data.get_cutout_image_times().get("balance")
  405. print("remaining_times", remaining_times)
  406. if remaining_times <= 0:
  407. raise UnicornException("次数不足,处理失败")
  408. self.get_online_data.dispose_point("sub")
  409. cut_image = self.r_ali.get_image_cut(
  410. file_path=None, out_file_path=None, original_im=original_pic.im
  411. )
  412. success_path = ""
  413. if cut_image is None:
  414. cut_status = False
  415. self.get_online_data.dispose_point("add")
  416. else:
  417. self.add_log("预抠图处理结束")
  418. cut_status = True
  419. save_root_path = "{}/已扣图".format(self.root_path)
  420. self.check_path(save_root_path)
  421. if self.windows.output_type == 1:
  422. background = Image.new("RGBA", cut_image.size, (255, 255, 255, 255))
  423. cut_image = Image.alpha_composite(background, cut_image)
  424. resize_width, resize_height = disposeWH(cut_image.convert("RGB"), 1024)
  425. cut_image = cut_image.resize((resize_width, resize_height))
  426. new_bg = Image.new("RGB", (1024, 1024), (255, 255, 255))
  427. cut_image = cut_image.convert("RGB").copy()
  428. width, height = cut_image.size
  429. offset = ((1024 - width) // 2, (1024 - height) // 2)
  430. new_bg.paste(cut_image, offset)
  431. cut_image = new_bg.copy()
  432. success_path = "{}/{}.png".format(save_root_path, self.file_name)
  433. cut_image.save(success_path)
  434. image_data["status"] = cut_status
  435. image_data["success_path"] = success_path
  436. return image_data
  437. def get_image_cut_cloths(self, image_data):
  438. self.file_path = image_data["file_path"]
  439. self.file = os.path.split(self.file_path)[1]
  440. self.root_path = image_data["root_path"]
  441. self.file_name = image_data["file_name"]
  442. original_pic = Picture(self.file_path)
  443. original_pic.im = self.get_image_orientation(original_pic.im)
  444. original_pic.x, original_pic.y = original_pic.im.size
  445. original_pic.im = original_pic.im.convert("RGB")
  446. image_deal_info = {}
  447. image_deal_info["原始图片大小"] = (original_pic.x, original_pic.y)
  448. self.add_log("开始预抠图处理")
  449. remaining_times_obj = self.get_online_data.get_cutout_image_times()
  450. if remaining_times_obj == False:
  451. raise UnicornException("获取可用次数失败,请检查是否登录")
  452. remaining_times = remaining_times_obj.get("balance")
  453. if remaining_times <= 0:
  454. raise UnicornException("次数不足,处理失败")
  455. self.get_online_data.dispose_point("sub")
  456. cut_images = self.r_ali.get_image_cut_cloths(
  457. file_path=None, out_file_path=None, original_im=original_pic.im
  458. )
  459. success_path = ""
  460. if cut_images is None or len(cut_images) == 0:
  461. cut_status = False
  462. self.get_online_data.dispose_point("add")
  463. else:
  464. self.add_log("预抠图处理结束")
  465. cut_status = True
  466. save_root_path = "{}/已扣图".format(self.root_path)
  467. self.check_path(save_root_path)
  468. save_file_path = "{}/{}".format(save_root_path, self.file_name)
  469. self.check_path(save_file_path)
  470. success_path = save_file_path
  471. for idx, item in enumerate(cut_images):
  472. cn_name = item.get("cn_name")
  473. image_obj = item.get("image_obj")
  474. if self.windows.output_type == 1:
  475. background = Image.new("RGBA", image_obj.size, (255, 255, 255, 255))
  476. image_obj = Image.alpha_composite(background, image_obj)
  477. resize_width, resize_height = disposeWH(
  478. image_obj.convert("RGB"), 1024
  479. )
  480. image_obj = image_obj.resize((resize_width, resize_height))
  481. new_bg = Image.new("RGB", (1024, 1024), (255, 255, 255))
  482. image_obj = image_obj.convert("RGB").copy()
  483. width, height = image_obj.size
  484. offset = ((1024 - width) // 2, (1024 - height) // 2)
  485. new_bg.paste(image_obj, offset)
  486. image_obj = new_bg.copy()
  487. image_obj.save("{}/{}.png".format(save_file_path, cn_name))
  488. image_data["status"] = cut_status
  489. image_data["success_path"] = success_path
  490. return image_data
  491. def get_image_orientation(self, img):
  492. # 获取EXIF数据
  493. exif = img._getexif()
  494. if exif is not None:
  495. # EXIF标签274对应的是Orientation
  496. orientation = exif.get(0x0112)
  497. if orientation == 2:
  498. # 水平翻转
  499. img = img.transpose(Image.FLIP_LEFT_RIGHT)
  500. elif orientation == 3:
  501. # 旋转180度
  502. img = img.rotate(180, expand=True)
  503. elif orientation == 4:
  504. # 垂直翻转
  505. img = img.transpose(Image.FLIP_TOP_BOTTOM)
  506. elif orientation == 5:
  507. # 水平翻转后顺时针旋转90度
  508. img = img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_270)
  509. elif orientation == 6:
  510. # 顺时针旋转90度
  511. img = img.transpose(Image.ROTATE_270)
  512. elif orientation == 7:
  513. # 水平翻转后逆时针旋转90度
  514. img = img.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.ROTATE_90)
  515. elif orientation == 8:
  516. # 逆时针旋转90度
  517. img = img.transpose(Image.ROTATE_90)
  518. else:
  519. print("没有EXIF数据或没有方向信息")
  520. orientation = 1
  521. return img