deal_one_image.py 20 KB

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