deal_one_image.py 19 KB

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