Bladeren bron

抠图模式处理

rambo 1 jaar geleden
bovenliggende
commit
6b8f42f465
5 gewijzigde bestanden met toevoegingen van 115 en 64 verwijderingen
  1. 11 5
      python/api.py
  2. 1 0
      python/models.py
  3. 24 3
      python/services/deal_cutout.py
  4. 76 51
      python/services/deal_one_image.py
  5. 3 5
      python/services/other/remove_bg_ali.py

+ 11 - 5
python/api.py

@@ -31,7 +31,9 @@ async def checkSelect(params: CheckSelectImages):
 async def segmentImages(params: SegmentImages):
     image_type = params.image_type
     segment_type = params.segment_type
+    output_type = params.output_type
     need_cutout_images = params.need_cutout_images
+    result = None
     if len([x for x in need_cutout_images if x["need_cutout"]]) == 0:
         raise UnicornException("您所选文件夹下没有jpg图片,或对应图片已扣图")
     if image_type == 1 and segment_type == 1:
@@ -41,14 +43,18 @@ async def segmentImages(params: SegmentImages):
         # 服装抠图
         # need_cutout_images = service.check_need_cutout_images(file_path)
         deal_cutout_cloth.need_cutout_images = need_cutout_images
-        deal_cutout_cloth.startDispose()
+        deal_cutout_cloth.output_type = output_type
+        result = deal_cutout_cloth.startDispose()
     elif image_type == 0 and segment_type == 1:
         deal_cutout_mode = DealCutout()
         # 通用-精细化抠图
         deal_cutout_mode.need_cutout_images = need_cutout_images
-        deal_cutout_mode.startDispose()
+        deal_cutout_mode.output_type = output_type
+        result = deal_cutout_mode.startDispose()
     elif image_type == 0 and segment_type == 0:
         # 通用-普通抠图
-        # need_cutout_images = service.check_need_cutout_images(file_path)
-        pass
-    return success(need_cutout_images)
+        deal_cutout_mode = DealCutout()
+        deal_cutout_mode.need_cutout_images = need_cutout_images
+        deal_cutout_mode.output_type = output_type
+        result = deal_cutout_mode.normalMode()
+    return success({"result": result})

+ 1 - 0
python/models.py

@@ -33,4 +33,5 @@ class SegmentImages(BaseModel):
     # 抠图
     image_type: int = Field(default=0, description="图像类型;0非服装;1服装")
     segment_type: int = Field(default=0, description="抠图精细度;0普通;1精细")
+    output_type: int = Field(default=0, description="抠图精细度;0透明;1白底")
     need_cutout_images: list = Field(default=None, description="图像地址集合")

+ 24 - 3
python/services/deal_cutout.py

@@ -17,6 +17,7 @@ class DealCutout:
         self.get_online_data = GetOnlineData()
         self.is_upload_pic_num = 0
         self.is_deal_num = 0
+        self.output_type = 0
         # 图片列表
         self.upload_pic_dict = {}
         self.logger = MyLogger().logger
@@ -24,16 +25,32 @@ class DealCutout:
     def startDispose(self):
         self.get_online_data.refresh_headers()
         num = 0
+        result_array = []
         for image_data in self.need_cutout_images:
             num += 1
             upload_pic_dict = {}
             upload_pic_dict = DealOneImageBeforehand(
                 image_data=image_data, lock=self.lock, windows=self, num=num
             ).run(upload_pic_dict)
-            print("upload_pic_dict", upload_pic_dict)
-            DealOneImage(
+            result = DealOneImage(
                 image_data=image_data, lock=self.lock, windows=self, num=num
             ).run(image_data, upload_pic_dict)
+            result_array.append(result)
+        return result_array
+
+    def normalMode(self):
+        """普通模式"""
+        self.get_online_data.refresh_headers()
+        num = 0
+        result_array = []
+        for image_data in self.need_cutout_images:
+            num += 1
+            result = DealOneImageBeforehand(
+                image_data=image_data, lock=self.lock, windows=self, num=num
+            ).get_image_cut_noraml(image_data)
+            result_array.append(result)
+        return result_array
+
 
 class DealCloths:
 
@@ -41,6 +58,7 @@ class DealCloths:
         super().__init__()
         self.lock = threading.Lock()
         self.need_cutout_images = {}
+        self.output_type = 0
         self.state = 2  # 1进行中 2停止
         self.get_online_data = GetOnlineData()
         self.is_upload_pic_num = 0
@@ -52,10 +70,13 @@ class DealCloths:
     def startDispose(self):
         self.get_online_data.refresh_headers()
         num = 0
+        result_array = []
         for image_data in self.need_cutout_images:
             num += 1
             upload_pic_dict = {}
             hand = DealOneImageBeforehand(
                 image_data=image_data, lock=self.lock, windows=self, num=num
             )
-            upload_pic_dict = hand.get_image_cut_cloths()
+            upload_pic_dict = hand.get_image_cut_cloths(image_data)
+            result_array.append(upload_pic_dict)
+        return result_array

+ 76 - 51
python/services/deal_one_image.py

@@ -127,6 +127,8 @@ class DealOneImage(Base):
         self.file = os.path.split(self.file_path)[1]
         self.root_path = image_data["root_path"]
         self.file_name = image_data["file_name"]
+        cut_status = False
+        success_path = ""
         # 直接调用抠图
         # 1、增加获取key,2、key需要加密、3、429报错 重试再来拿一个KEY
         self.add_log("开始处理")
@@ -179,20 +181,24 @@ class DealOneImage(Base):
                     image_deal_info["抠图扩边后位置"][1],
                 ),
             )
+            if self.windows.output_type == 1:
+                background = Image.new("RGBA", _img_im.size, (255, 255, 255, 255))
+                _img_im = Image.alpha_composite(background, _img_im)
+            cut_status = True
+            success_path = out_path
             _img_im.save(out_path)
 
         except BaseException as e:
-            # print(e)
             text = "{} 图片处理错误,代码44".format(e)
             self.add_log(text)
             self.send_info(text=text, is_success=False, need_point_return=True)
-            _data = {"text": "出错/超时", "info": text, "status": False}
-            return _data
+            cut_status = False
 
         self.add_log(text="本张耗时:{}".format(time.time() - s))
         self.send_info(text="抠图已完成", is_success=True)
-        result = {"text": "已完成", "info": "", "status": True}
-        return result
+        image_data["status"] = cut_status
+        image_data["success_path"] = success_path
+        return image_data
 
     def runPiXian(self, num, original_im):
         """执行pixian抠图"""
@@ -346,8 +352,6 @@ class DealOneImageBeforehand(Base):
             cut_image = self.r_ali.get_image_cut(
                 file_path=None, out_file_path=None, original_im=original_pic.im
             )
-            cut_image.save("XX1.png")
-
             self.add_log("预抠图处理结束")
 
             x1, y1, x2, y2 = cut_image.getbbox()
@@ -391,7 +395,51 @@ class DealOneImageBeforehand(Base):
                 image_deal_info["二次抠图是否缩放"] = False
         return cut_image, image_deal_info
 
-    def get_image_cut_cloths(self):
+    def get_image_cut_noraml(self, image_data):
+        """普通模式抠图"""
+        self.file_path = image_data["file_path"]
+        self.file = os.path.split(self.file_path)[1]
+        self.root_path = image_data["root_path"]
+        self.file_name = image_data["file_name"]
+        original_pic = Picture(self.file_path)
+        original_pic.im = self.get_image_orientation(original_pic.im)
+        original_pic.x, original_pic.y = original_pic.im.size
+
+        original_pic.im = original_pic.im.convert("RGB")
+        image_deal_info = {}
+        image_deal_info["原始图片大小"] = (original_pic.x, original_pic.y)
+        self.add_log("开始预抠图处理")
+        remaining_times = self.get_online_data.get_cutout_image_times().get("balance")
+        print("remaining_times", remaining_times)
+        if remaining_times <= 0:
+            raise UnicornException("次数不足,处理失败")
+        self.get_online_data.dispose_point("sub")
+        cut_image = self.r_ali.get_image_cut(
+                file_path=None, out_file_path=None, original_im=original_pic.im
+            )
+        success_path = ""
+        if cut_image is None:
+            cut_status = False
+            self.get_online_data.dispose_point("add")
+        else:
+            self.add_log("预抠图处理结束")
+            cut_status = True
+            save_root_path = "{}/已扣图".format(self.root_path)
+            self.check_path(save_root_path)
+            if self.windows.output_type == 1:
+                background = Image.new("RGBA", cut_image.size, (255, 255, 255, 255))
+                cut_image = Image.alpha_composite(background, cut_image)
+            success_path = "{}/{}.png".format(save_root_path, self.file_name)
+            cut_image.save(success_path)
+        image_data["status"] = cut_status
+        image_data["success_path"] = success_path
+        return image_data
+
+    def get_image_cut_cloths(self, image_data):
+        self.file_path = image_data["file_path"]
+        self.file = os.path.split(self.file_path)[1]
+        self.root_path = image_data["root_path"]
+        self.file_name = image_data["file_name"]
         original_pic = Picture(self.file_path)
         original_pic.im = self.get_image_orientation(original_pic.im)
         original_pic.x, original_pic.y = original_pic.im.size
@@ -408,51 +456,28 @@ class DealOneImageBeforehand(Base):
         cut_images = self.r_ali.get_image_cut_cloths(
             file_path=None, out_file_path=None, original_im=original_pic.im
         )
-        if cut_images is None:
+        success_path = ""
+        if cut_images is None or len(cut_images) == 0:
+            cut_status = False
             self.get_online_data.dispose_point("add")
-        self.add_log("预抠图处理结束")
-        print("cut_images", cut_images)
-        return
-        x1, y1, x2, y2 = cut_image.getbbox()
-        image_deal_info["鞋子原始位置"] = (x1, y1, x2, y2)
-        o_w, o_h = cut_image.size
-        image_deal_info["鞋子原始抠图后大小"] = (o_w, o_h)
-        # 扩边处理
-        _w, _h = x2 - x1, y2 - y1
-        out_px = 0.025
-        _w, _h = int(out_px * _w), int(out_px * _h)
-        n_x1, n_y1, n_x2, n_y2 = x1 - _w, y1 - _h, x2 + _w, y2 + _h
-        if n_x1 < 0:
-            n_x1 = 0
-        if n_y1 < 0:
-            n_y1 = 0
-        if n_x2 > o_w:
-            n_x2 = o_w
-        if n_y2 > o_h:
-            n_y2 = o_h
-        image_deal_info["抠图扩边后位置"] = (n_x1, n_y1, n_x2, n_y2)
-        cut_image = original_pic.im.crop(image_deal_info["抠图扩边后位置"])
-
-        image_deal_info["抠图扩边后图片大小"] = cut_image.size
-        x, y = image_deal_info["抠图扩边后图片大小"]
-        # max_size = 32000000
-        max_size = 12000000
-        if x * y > max_size:
-            r = max_size / (x * y)
-            size = (int(x * r), int(y * r))
-            self.add_log(
-                text="图片进行压缩,压缩前:{},压缩后:{}".format(
-                    image_deal_info["抠图扩边后图片大小"], size
-                )
-            )
-            image_deal_info["抠图扩边后PIL对象"] = copy.deepcopy(cut_image)
-            cut_image = cut_image.resize(size=size)
-            # print(cut_image.size)
-            # print(image_deal_info["抠图扩边后PIL对象"].size)
-            image_deal_info["二次抠图是否缩放"] = True
         else:
-            image_deal_info["二次抠图是否缩放"] = False
-        return cut_image, image_deal_info
+            self.add_log("预抠图处理结束")
+            cut_status = True
+            save_root_path = "{}/已扣图".format(self.root_path)
+            self.check_path(save_root_path)
+            save_file_path = "{}/{}".format(save_root_path, self.file_name)
+            self.check_path(save_file_path)
+            success_path = save_file_path
+            for idx, item in enumerate(cut_images):
+                cn_name = item.get("cn_name")
+                image_obj = item.get("image_obj")
+                if self.windows.output_type == 1:
+                    background = Image.new("RGBA", image_obj.size, (255, 255, 255, 255))
+                    image_obj = Image.alpha_composite(background, image_obj)
+                image_obj.save("{}/{}.png".format(save_file_path, cn_name))
+        image_data["status"] = cut_status
+        image_data["success_path"] = success_path
+        return image_data
 
     def get_image_orientation(self, img):
         # 获取EXIF数据

+ 3 - 5
python/services/other/remove_bg_ali.py

@@ -220,10 +220,10 @@ class RemoveBgALi(object):
             if new_pic.y > 2000:
                 after_need_resize = True
                 new_pic.resize_by_heigh(heigh=2000)
-        body = self.segment.get_no_bg_cloths(_im=new_pic.im)
-        body = eval(str(body))
-        clothsArray = []
         try:
+            body = self.segment.get_no_bg_cloths(_im=new_pic.im)
+            body = eval(str(body))
+            clothsArray = []
             Elements = body["Data"]["Elements"]
             for idx, clothItem in enumerate(Elements):
                 if idx == 0:
@@ -259,7 +259,6 @@ class RemoveBgALi(object):
                         )
         except BaseException as e:
             # todo 处理失败,需要删除过程图片
-            print(e)
             return None
         image_arrs = []
         for _, item in enumerate(clothsArray):
@@ -271,7 +270,6 @@ class RemoveBgALi(object):
                 _img_im = self.clothsDispose(
                     _img_im, original_pic=original_pic, out_file_path=out_file_path
                 )
-            _img_im.save(f"{cn_name}.png")
             image_arrs.append({"image_obj": _img_im, "type": type, "cn_name": cn_name})
         return image_arrs