Kaynağa Gözat

人体分割抠图

dsx 2 yıl önce
ebeveyn
işleme
f73e2865b3

+ 6 - 0
pom.xml

@@ -140,6 +140,12 @@
             <version>6.8.1</version>
         </dependency>
 
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>imageseg20191230</artifactId>
+            <version>1.0.5</version>
+        </dependency>
+
     </dependencies>
 
     <dependencyManagement>

+ 22 - 0
src/main/java/com/fdkankan/scene/bean/BodySegmentStatusBean.java

@@ -0,0 +1,22 @@
+package com.fdkankan.scene.bean;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class BodySegmentStatusBean {
+
+    private String uuid;
+
+    private Integer status;
+
+    private String imageUrl;
+
+
+
+}

+ 29 - 5
src/main/java/com/fdkankan/scene/controller/SceneController.java

@@ -2,6 +2,8 @@ package com.fdkankan.scene.controller;
 
 
 import com.fdkankan.common.constant.SceneInfoReqType;
+import com.fdkankan.scene.annotation.CheckPermit;
+import com.fdkankan.scene.service.ISceneService;
 import com.fdkankan.web.response.ResultData;
 import com.fdkankan.scene.service.ISceneEditInfoService;
 import com.fdkankan.scene.service.IScenePlusService;
@@ -12,11 +14,8 @@ import com.fdkankan.scene.vo.SceneInfoVO;
 import com.fdkankan.web.controller.BaseController;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 /**
  * <p>
@@ -34,6 +33,8 @@ public class SceneController extends BaseController {
     private ISceneEditInfoService sceneEditInfoService;
     @Autowired
     private IScenePlusService scenePlusService;
+    @Autowired
+    private ISceneService sceneService;
 
     /**
      * <p>
@@ -78,5 +79,28 @@ public class SceneController extends BaseController {
         return scenePlusService.downLoadZSData(sceneNum);
     }
 
+    /**
+     * 上传人体抠图原图
+     * @param num
+     * @param file
+     * @return
+     * @throws Exception
+     */
+    @PostMapping(value = "/uploadBodySegment")
+    public ResultData uploadBodySegment(@RequestParam(value = "num") String num,
+                                     @RequestParam("file") MultipartFile file) throws Exception {
+        return sceneService.uploadBodySegment(num, file);
+    }
+
+    /**
+     * 获取人体抠图提取状态
+     * @return ResultData
+     * @throws Exception
+     */
+    @PostMapping(value = "/getBodySegmentStatus")
+    public ResultData getBodySegmentStatus(@RequestParam(value = "serialNum") String uuid) throws Exception {
+        return sceneService.getBodySegmentStatus(uuid);
+    }
+
 }
 

+ 23 - 0
src/main/java/com/fdkankan/scene/httpclient/MyClient.java

@@ -0,0 +1,23 @@
+package com.fdkankan.scene.httpclient;
+
+
+import com.dtflys.forest.annotation.Get;
+import com.dtflys.forest.annotation.Var;
+import com.dtflys.forest.callback.OnProgress;
+import com.dtflys.forest.extensions.DownloadFile;
+
+import java.io.File;
+
+public interface MyClient {
+
+    /**
+     * 在方法上加上@DownloadFile注解
+     * dir属性表示文件下载到哪个目录
+     * filename属性表示文件下载成功后以什么名字保存,如果不填,这默认从URL中取得文件名
+     * OnProgress参数为监听上传进度的回调函数
+     */
+    @Get(url = "{url}")
+    @DownloadFile(dir = "{dir}", filename = "{filename}")
+    File downloadFile(@Var("url") String url, @Var("dir") String dir, @Var("filename")String filename);
+
+}

+ 26 - 5
src/main/java/com/fdkankan/scene/listener/RabbitMqListener.java

@@ -1,8 +1,10 @@
 package com.fdkankan.scene.listener;
 
 import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
 import com.fdkankan.scene.entity.DownloadTourVideo;
 import com.fdkankan.scene.service.IDownloadTourVideoService;
+import com.fdkankan.scene.service.ISceneService;
 import com.rabbitmq.client.Channel;
 import java.nio.charset.StandardCharsets;
 import lombok.extern.slf4j.Slf4j;
@@ -28,11 +30,13 @@ public class RabbitMqListener {
     @Value("${queue.scene.transfer-tour-video}")
     private String downloadTourVideoQueue;
 
+    @Value("${queue.bodySegment:body-segment}")
+    private String bodySegmentQueueName;
+
     @Autowired
     private IDownloadTourVideoService downloadTourVideoService;
-
-
-
+    @Autowired
+    private ISceneService sceneService;
 
     /**
      * 开启了手动确认模式,如果没有手动确认,消费者不会重试,当服务重启时会再次消费,因为rabbitmq认为你还没有处理完你的业务
@@ -59,6 +63,25 @@ public class RabbitMqListener {
      * concurrency = "3"    设置消费线程数,每个线程每次只拉取一条消息消费
      */
     @RabbitListener(
+            queuesToDeclare = @Queue("${queue.bodySegment}"),
+            concurrency = "${maxThread.bodySegment}"
+    )
+    public void bodySegment(Channel channel, Message message) throws Exception {
+        String messageId = message.getMessageProperties().getMessageId();
+        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
+        log.info("开始消费消息,id:{},queue:{},content:{}", messageId, bodySegmentQueueName, msg);
+        JSONObject jsonObject = JSON.parseObject(msg);
+        sceneService.bodySegmentHandler(jsonObject.getString("imgUrl"), jsonObject.getString("uuid"));
+        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
+        log.info("结束消费消息,id:{}", messageId);
+    }
+
+    /**
+     * 开启了手动确认模式,如果没有手动确认,消费者不会重试,当服务重启时会再次消费,因为rabbitmq认为你还没有处理完你的业务
+     * queuesToDeclare = @Queue("${queue.modeling.modeling-test}"),  如果队列不不存在会自动创建队列
+     * concurrency = "3"    设置消费线程数,每个线程每次只拉取一条消息消费
+     */
+    @RabbitListener(
         queuesToDeclare = @Queue("test_dsx")
     )
     public void test(Channel channel, Message message) throws Exception {
@@ -72,6 +95,4 @@ public class RabbitMqListener {
     }
 
 
-
-
 }

+ 16 - 0
src/main/java/com/fdkankan/scene/service/ISceneService.java

@@ -0,0 +1,16 @@
+package com.fdkankan.scene.service;
+
+import com.fdkankan.scene.bean.BodySegmentStatusBean;
+import com.fdkankan.web.response.ResultData;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.multipart.MultipartFile;
+
+public interface ISceneService {
+
+    ResultData uploadBodySegment(String num, MultipartFile file) throws Exception;
+
+    void bodySegmentHandler(String imgUrl, String uuid);
+
+    ResultData getBodySegmentStatus(String uuid);
+
+}

Dosya farkı çok büyük olduğundan ihmal edildi
+ 123 - 1473
src/main/java/com/fdkankan/scene/service/impl/SceneServiceImpl.java


+ 95 - 0
src/main/java/com/fdkankan/scene/util/OssBodySegmentUtil.java

@@ -0,0 +1,95 @@
+package com.fdkankan.scene.util;
+
+import cn.hutool.core.io.FileUtil;
+import cn.hutool.http.HttpUtil;
+import com.aliyun.imageseg20191230.models.SegmentBodyResponse;
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClientBuilder;
+import com.aliyun.tea.TeaException;
+import com.fdkankan.common.util.FileUtils;
+import com.fdkankan.scene.httpclient.MyClient;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cloud.context.config.annotation.RefreshScope;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+@Slf4j
+@Component
+@RefreshScope
+public class OssBodySegmentUtil {
+
+    @Value("${oss.bodySegment.point:imageseg.cn-shanghai.aliyuncs.com}")
+    private String endPoint;
+
+    @Value("${oss.key:LTAIUrvuHqj8pvry}")
+    private String accessKeyId;
+
+    @Value("${oss.secrey:JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4}")
+    private String accessKeySecret;
+
+    @Value("${oss.bodySegment.bucket:4dkankan-huadong}")
+    private String bucket;
+
+    @Resource
+    private MyClient myClient;
+
+    public void uploadOss(String filePath, String key){
+        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
+        try {
+            File file = new File(filePath);
+            if (!file.exists()) {
+                log.error("要上传的文件不存在:" + filePath);
+                return;
+            }
+            ossClient.putObject(bucket, key, new File(filePath));
+        } catch (Exception e) {
+            log.error(e.toString() + filePath);
+        } finally {
+            ossClient.shutdown();
+        }
+    }
+
+    public void extracted(String imageUrl, String dir, String fileName) throws Exception {
+        com.aliyun.imageseg20191230.Client client = this.createClient();
+        com.aliyun.imageseg20191230.models.SegmentBodyRequest segmentBodyRequest =
+                new com.aliyun.imageseg20191230.models.SegmentBodyRequest().setImageURL(imageUrl);
+        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
+        // 复制代码运行请自行打印 API 的返回值
+        SegmentBodyResponse segmentBodyResponse = client.segmentBodyWithOptions(segmentBodyRequest, runtime);
+        String imageURL = segmentBodyResponse.getBody().getData().getImageURL();
+        log.info("人体抠图imageURL:{}", imageURL);
+//        HttpUtil.downloadFile(imageURL, FileUtil.file(file));
+        myClient.downloadFile(imageURL, dir, fileName);
+
+//        FileUtils.downLoadFromUrl(imageURL, "1.jpg","D:\\test");
+//        byte[] aaa = FileUtils.getBytesFromUrl(imageURL);
+//        FileUtil.writeBytes(aaa, file);
+
+    }
+
+    public static void main(String[] args) {
+        FileUtils.downLoadFromUrl("http://vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com/segment-body/2023-02-24/5d44fe44-308c-44c3-8e1d-2d4cbe601f86/image.png?Expires=1677208715&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRpDvh1&Signature=4ZyzaOz6W1nBD9s3KQuFN10c%2BPw%3D",
+                "1.png","D:\\test");
+    }
+
+    /**
+     * 使用AK&SK初始化账号Client
+     * @return Client
+     * @throws Exception
+     */
+    public com.aliyun.imageseg20191230.Client createClient() throws Exception {
+        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
+                // 必填,您的 AccessKey ID
+                .setAccessKeyId(accessKeyId)
+                // 必填,您的 AccessKey Secret
+                .setAccessKeySecret(accessKeySecret);
+        // 访问的域名
+        config.endpoint = this.endPoint;
+        return new com.aliyun.imageseg20191230.Client(config);
+    }
+
+}

+ 97 - 0
src/main/java/com/fdkankan/scene/util/test.java

@@ -0,0 +1,97 @@
+package com.fdkankan.scene.util;
+// This file is auto-generated, don't edit it. Thanks.
+
+import cn.hutool.core.io.FileUtil;
+import cn.hutool.core.thread.ThreadUtil;
+import cn.hutool.http.HttpUtil;
+import com.aliyun.imageseg20191230.Client;
+import com.aliyun.imageseg20191230.models.SegmentBodyResponse;
+import com.aliyun.tea.TeaException;
+import com.aliyun.teautil.Common;
+
+import java.io.File;
+
+public class test {
+
+    /**
+     * 使用AK&SK初始化账号Client
+     *
+     * @param accessKeyId
+     * @param accessKeySecret
+     * @return Client
+     * @throws Exception
+     */
+    public static com.aliyun.imageseg20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
+        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
+                // 必填,您的 AccessKey ID
+                .setAccessKeyId(accessKeyId)
+                // 必填,您的 AccessKey Secret
+                .setAccessKeySecret(accessKeySecret);
+        // 访问的域名
+        config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
+        return new com.aliyun.imageseg20191230.Client(config);
+    }
+
+    public static void main(String[] args_) throws Exception {
+
+        java.util.List<String> args = java.util.Arrays.asList(args_);
+        // 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
+        com.aliyun.imageseg20191230.Client client = test.createClient("LTAIUrvuHqj8pvry", "JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4");
+        ThreadUtil.execAsync(() -> {
+            extracted(client, "https://4dkankan-huadong.oss-cn-shanghai.aliyuncs.com/segment/1.jpg", "1");
+
+        });
+        ThreadUtil.execAsync(() -> {
+            extracted(client, "https://4dkankan-huadong.oss-cn-shanghai.aliyuncs.com/segment/2.jpg", "2");
+
+        });
+        ThreadUtil.sleep(1000);
+        ThreadUtil.execAsync(() -> {
+            extracted(client, "https://4dkankan-huadong.oss-cn-shanghai.aliyuncs.com/segment/3.jpg", "3");
+
+        });
+        ThreadUtil.execAsync(() -> {
+            extracted(client, "https://4dkankan-huadong.oss-cn-shanghai.aliyuncs.com/segment/4.webp", "4");
+
+        });
+//      ThreadUtil.sleep(2000);
+//      ThreadUtil.sleep(3000);
+
+//      ThreadUtil.sleep(4000);
+
+
+    }
+
+    private static void extracted(Client client, String imageUrl, String imgName) {
+
+        com.aliyun.imageseg20191230.models.SegmentBodyRequest segmentBodyRequest = new com.aliyun.imageseg20191230.models.SegmentBodyRequest()
+                .setImageURL(imageUrl);
+        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
+        try {
+            // 复制代码运行请自行打印 API 的返回值
+            long stime = System.currentTimeMillis();
+            System.out.println("开始-----------" + imgName);
+            SegmentBodyResponse segmentBodyResponse = client.segmentBodyWithOptions(segmentBodyRequest, runtime);
+            String imageURL = segmentBodyResponse.getBody().getData().getImageURL();
+            long etime = System.currentTimeMillis();
+            System.out.printf("执行时长:%d 毫秒.----%s", (etime - stime), imgName);
+            File file = FileUtil.file("C:\\Users\\4DAGE\\Downloads\\抠像测试\\抠像测试\\1\\" + imgName + ".png");
+            if (FileUtil.exist(file)) {
+                FileUtil.del(file);
+            }
+            System.out.println(imageURL);
+            ThreadUtil.sleep(1000);
+            HttpUtil.downloadFile(imageURL, FileUtil.file(file));
+        } catch (TeaException error) {
+            // 如有需要,请打印 error
+            String s = Common.assertAsString(error.message);
+            System.out.println("错误1" + s);
+        } catch (Exception _error) {
+            TeaException error = new TeaException(_error.getMessage(), _error);
+            // 如有需要,请打印 error
+            String s = Common.assertAsString(error.message);
+            System.out.println("错误2" + s);
+
+        }
+    }
+}