视觉学习第三天

简介: 电子相册笔记

电子相册

目录结构

image-20200926161344287

  • common:是存放一些常量
  • config:路径配置,数据配置
  • controller:请求后台数据
  • service :图片的保存和处理
  • utils:MD5工具类
  • resources:放置了些静态文件和日志文件

前提要求

要购买人脸识别服务,不然用不了

环境

pom的依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.67</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.14</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aliyun/facebody -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>facebody</artifactId>
            <version>0.0.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.aliyun/imagerecog -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>imagerecog</artifactId>
            <version>0.0.5</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

ExpressionEnum

public enum ExpressionEnum {
    neutral ("neutral","中性"),
    happiness("happiness","高兴"),
    surprise("surprise","惊讶"),
    sadness("sadness","伤心"),
    anger("anger","生气"),
    disgust("disgust","厌恶"),
    fear("害怕","害怕");

    String name;
    String nameEn;

    ExpressionEnum(String nameEn,String name){
        this.name = name;
        this.nameEn = nameEn;
    }

    public static String getNameByNameEn(String nameEn){
        for (ExpressionEnum expressionEnum : ExpressionEnum.values()){
            if (expressionEnum.nameEn.equals(nameEn)){
                return expressionEnum.name;
            }
        }
        return "";
    }
}

ResourseService

@Service
@Data
@Slf4j
public class ResourceService {

    private String scene;

    @Value("./data")
    private String storagePath;

    @Value("./img")
    private String imagePath;

    static final String fileName = "data.json";

    private LabelModel labelModel;

    @Autowired
    private VisionService visionService;

    @PostConstruct
    public void loadMetaData(){
        log.info("load");
        try {
            FileInputStream inputStream = new FileInputStream(storagePath + fileName);
            labelModel = JSONObject.parseObject(inputStream, LabelModel.class);
        } catch (IOException e) {
            log.error(e.toString());
            labelModel = new LabelModel();
        }
    }

    @PreDestroy
    public void saveMetaData(){
        log.info("save");
        try {
            System.out.println(JSON.toJSONString(labelModel));
            FileOutputStream outputStream = new FileOutputStream(storagePath + fileName);
            outputStream.write(JSON.toJSONBytes(labelModel));
            outputStream.close();
        } catch (IOException e) {
            log.error(e.toString());
        }
    }

    public List<String> getPhotosByCateAndLabel(String cate,String label){
        return getAccessPath(labelModel.getImgByCate(cate));
    }

    public List<String> getAccessPath(List<String> imgs){
        List<String> result = new ArrayList<>();
        imgs.stream().forEach(img -> {
            result.add(String.format("/img/%s",img));
        });
        return result;
    }

    public List<String> getPhotosByCate(String cate) {
        return getAccessPath(labelModel.getImgByCate(cate));
    }

    public List<String> getAllPhotos(){
        return getAccessPath(labelModel.getAllImg());
    }

    public Object getAllCates(){
        return labelModel.cateMap;
    }


    public void saveAndRecognizeImage(String fileName, InputStream inputStream){
        log.info("saveImage");
        try {
            //识别场景
            inputStream.reset();
            inputStream.mark(0);
            List<String> scenes = visionService.recognizeScene(inputStream);
            labelModel.addImg(LabelModel.SCENE,fileName,scenes);

            inputStream.reset();
            inputStream.mark(0);
            List<String> expressions = visionService.recognizeExpression(inputStream);
            labelModel.addImg(LabelModel.EXPRESSION,fileName,expressions);

            //重复利用InputStream需要reset,mark操作
            inputStream.reset();
            inputStream.mark(0);

            //保存文件
            System.out.println(imagePath+fileName);
            FileOutputStream outputStream = new FileOutputStream(imagePath + fileName);
            IOUtils.copy(inputStream,outputStream);

            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    }



    @Data
    static class LabelModel{
        static final String SCENE = "scene";
        static final String EXPRESSION = "expression";
        static final String STYLE = "style";

        //保存不同场景标签包含的图片
        private Map<String,Set<String>> sceneMap;
        //保存不同表情包含有的图片
        private Map<String,Set<String>> expressionMap;

        //保存不同风格包含的图片
        private Map<String,Set<String>> styleMap;
        private Map<String,Set<String>> cateMap;

        //图片包含的标签
        //key:图片地址
        //value:Set中value值为:{[style| expression|style]}_{label},例如:style_怀旧
        private Map<String,Set<String>> imgLables;

        public LabelModel(){
            this.imgLables = new HashMap<>();
            this.sceneMap = new HashMap<>();
            this.expressionMap = new HashMap<>();
            this.styleMap = new HashMap<>();
            this.cateMap = new HashMap<>();
        }

        //获取所有的图片
        public List<String> getAllImg(){
            List<String> result = new ArrayList<>();
            imgLables.forEach((k,v)->{
                result.add(k);
            });

            return result.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }

        //获取图片的种类
        public List<String> getImgByCate(String cate){
            Map<String,Set<String>> data = new HashMap<>();
            switch (cate){
                case SCENE:{
                    data = sceneMap;
                    break;
                }
                case EXPRESSION:{
                    data = expressionMap;
                    break;
                }
                case STYLE:{
                    data = styleMap;
                    break;
                }
            }

            Set<String> result = new HashSet<>();
            data.forEach((k,d)->{
                result.addAll(d);
            });

            return result.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }


        public List<String> getImgByCateAndLabel(String cate,String label){
            System.out.println(cate);
            System.out.println(label);

            String key = String.format("%s_%s",cate,label);

            Set<String> result = new HashSet<>();
            switch (cate){
                case SCENE:{
                    result = sceneMap.get(key);
                    break;
                }
                case EXPRESSION:{
                    result = expressionMap.get(key);
                    break;
                }
                case STYLE:{
                    result = styleMap.get(key);
                    break;
                }
            }
            return result.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        }

        void addImg(String cate,String img,List<String> labels){
            for (String label : labels) {
                String item = String.format("%s_%s", cate, label);
                Set<String> imgSet = imgLables.getOrDefault(img, new HashSet<>());
                imgSet.add(item);
                imgLables.put(img, imgSet);
                switch (cate) {
                    case SCENE: {
                        Set<String> sceneSet = sceneMap.getOrDefault(item, new HashSet<>());
                        sceneSet.add(img);
                        sceneMap.put(item, sceneSet);
                        Set<String> cateSet = cateMap.getOrDefault(cate, new HashSet<>());
                        cateSet.add(label);
                        cateMap.put(cate, cateSet);
                        break;
                    }
                    case EXPRESSION: {
                        Set<String> expressionSet = expressionMap.getOrDefault(item, new HashSet<>());
                        expressionSet.add(img);
                        expressionMap.put(item, expressionSet);
                        Set<String> cateSet = cateMap.getOrDefault(cate, new HashSet<>());
                        cateSet.add(label);
                        cateMap.put(cate, cateSet);
                        break;
                    }
                    case STYLE: {
                        Set<String> styleSet = styleMap.getOrDefault(item, new HashSet<>());
                        styleSet.add(img);
                        styleMap.put(item, styleSet);
                        Set<String> cateSet = cateMap.getOrDefault(cate, new HashSet<>());
                        cateSet.add(label);
                        cateMap.put(cate, cateSet);
                        break;
                    }
                }
            }
        }


        void removeImg(String img) {
            Set<String> labels = imgLables.remove(img);
            labels.stream().forEach(label -> {
                String[] segs = label.split("_");
                String cate = segs[0];
                String labelKey = segs[1];
                switch (cate) {
                    case SCENE: {
                        sceneMap.get(labelKey).remove(img);
                        break;
                    }
                    case EXPRESSION: {
                        expressionMap.get(labelKey).remove(img);
                        break;
                    }
                    case STYLE: {
                        styleMap.get(labelKey).remove(img);
                        break;
                    }
                }
            });
        }
    }
}

VisionService

@Service
@Slf4j
public class VisionService {

    @Value("${aliyun.accessKeyId}")
    private String accessKey;

    @Value("${aliyun.accessKeySecret}")
    private String accessSecret;

    static String faceBodyEndpoint = "facebody";
    static String imageRecogEndpoint = "imagerecog";
    static String objectDetEndpoint = "objectdet";


    private Client getFaceBodyClient(String endpoint) throws Exception {
        Config config = new Config();
        config.accessKeyId = accessKey;
        config.accessKeySecret = accessSecret;
        config.type = "access_key";
        config.regionId = "cn-shanghai";
        config.endpointType = "internal";
        config.endpoint = String.format("%s.%s",endpoint,"cn-shanghai.aliyuncs.com");
        config.protocol = "http";
        return new Client(config);
    }

    private com.aliyun.imagerecog.Client getImageRecognClient(String endpoint) throws Exception {
        com.aliyun.imagerecog.models.Config config = new com.aliyun.imagerecog.models.Config();
        config.accessKeyId = accessKey;
        config.accessKeySecret = accessSecret;
        config.type = "access_key";
        config.regionId = "cn-shanghai";
        config.endpointType = "internal";
        config.endpoint = String.format("%s.%s",endpoint,"cn-shanghai.aliyuncs.com");
        config.protocol = "http";
        return new com.aliyun.imagerecog.Client(config);
    }

    public static InputStream getImageStream(String url) throws Exception{
        URLConnection conn = new URL(url).openConnection();
        conn.setConnectTimeout(10 * 1000);
        conn.setReadTimeout(10 * 1000);
        return conn.getInputStream();
    }

    public List<String> recognizeScene(InputStream inputStream) throws Exception {
        RecognizeSceneAdvanceRequest request = new RecognizeSceneAdvanceRequest();
        request.imageURLObject = inputStream;

        List<String> labels = new ArrayList<>();
        try {
            com.aliyun.imagerecog.Client client = getImageRecognClient(imageRecogEndpoint);
            RecognizeSceneResponse resp = client.recognizeSceneAdvance(request, new RuntimeObject());
            for (RecognizeSceneResponse.RecognizeSceneResponseDataTags tag: resp.data.tags) {
                labels.add(tag.value);
            }
        } catch (ClientException e) {
            log.error("ErrCode:{}, ErrMsg:{}, RequestId:{}", e.getErrCode(), e.getErrMsg(), e.getRequestId());
        }
        return labels;
    }

    public List<String> recognizeExpression(InputStream inputStream) throws Exception {
        RecognizeExpressionAdvanceRequest request = new RecognizeExpressionAdvanceRequest();
        request.imageURLObject = inputStream;

        List<String> labels = new ArrayList<>();
        try {
            Client client = getFaceBodyClient(faceBodyEndpoint);
            RecognizeExpressionResponse resp = client.recognizeExpressionAdvance(request, new RuntimeObject());
            for (RecognizeExpressionResponse.RecognizeExpressionResponseDataElements element : resp.data.elements) {
                labels.add(ExpressionEnum.getNameByNameEn(element.expression));
            }
        } catch (ClientException e) {
            log.error("ErrCode:{}, ErrMsg:{}, RequestId:{}", e.getErrCode(), e.getErrMsg(), e.getRequestId());
        }
        return labels;
    }


}

Controller

@RestController
@RequestMapping("/album/v1")
@Slf4j
public class AlbumController {

    @Autowired
    private VisionService visionService;

    @Autowired
    private ResourceService resourceService;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object getList() throws Exception {
        return resourceService.getAllPhotos();
    }


    @RequestMapping(value = "/allCates", method = RequestMethod.GET)
    public Object getCates() throws Exception {
        return resourceService.getAllCates();
    }

    @RequestMapping(value = "/getPhotosByCateAndLabel", method = RequestMethod.GET)
    public Object getPhotosByCateAndLabel(@RequestParam(name="cate") String cate, @RequestParam(name="tag") String tag) throws Exception {
        return resourceService.getPhotosByCateAndLabel(cate, tag);
    }

    @RequestMapping(value = "/getPhotosByCate", method = RequestMethod.GET)
    public Object getPhotosByCate(@RequestParam(name="cate") String cate) throws Exception {
        return resourceService.getPhotosByCate(cate);
    }

    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) throws Exception {
        //计算上传文件的md5值,作为文件名
        byte[] bytes = file.getBytes();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        String md5Str = Md5CaculateUtil.getMD5(inputStream);
        inputStream.reset();
        inputStream.mark(0);

        String fileName = file.getOriginalFilename();
        String fType = fileName.substring(fileName.lastIndexOf("."));
        fileName = String.format("%s%s", md5Str, fType);
        resourceService.saveAndRecognizeImage(fileName, inputStream);
        return fileName;
    }


}

前端是用vue来实现的界面

image-20200926162039892

相关文章
|
4天前
|
人工智能 API 内存技术
刚刚 DeepSeek V4.1 Flash 开启内测,1 分钟教你用上!
刚刚 DeepSeek 内测群发布了 DeepSeek V4.1 Flash 中间版本内测的消息,这次的模型采用了新的结构,原生支持多模态、能力更强、速度更快、且成本更低。
1670 5
|
8天前
|
人工智能 运维 BI
阿里云千问办公QwenWork深度解析:基于Qwen3.8,六大核心能力重构企业全自动化工作流与计费选型指南
传统AI办公工具大多停留在对话问答、文档摘要、简单文案生成层面,只能完成单点碎片化任务,无法自主拆解复杂业务流程,很难串联多工具、多文档、外部业务系统完成端到端完整工作交付。很多企业在落地AI办公的时候,需要组合多款不同工具,来回切换界面,手动复制粘贴中间结果,智能化改造落地门槛居高不下。千问办公QwenWork是整合多款智能体产品能力打造的一体化企业办公智能体平台,底层基座依托Qwen3.8大模型,打通桌面端Agent、云端Agent、企业协同Agent三种运行形态,不再局限简单问答,接收业务目标之后自主拆解任务步骤,调用各类工具,处理文档、表格、浏览器自动化、数据查询,直接输出可交付的办公
1616 1
|
5天前
|
SQL 人工智能 前端开发
QoderWake 1.0 正式发布:从桌面里的 Agent,到工作现场的数字员工
QoderWake v1.0正式发布:企业级数字员工团队平台。支持“一句话建岗”,预置10类特训岗位;Waker常驻钉钉/飞书群,@即响应、自动协作、跨任务记忆;具备定时/事件/API多触发方式与统一任务看板;已沉淀27.6万条记忆、12.3万项技能,助力组织实现人机协同增效。
716 1
|
17天前
|
人工智能 自然语言处理 安全
阿里云千问办公、Qoder Teams、Qoder CN区别与选择指南:模型能力、适用场景与最新活动参考
本文聚焦阿里云2026年推出的三款自研AI办公产品,清晰拆解千问办公、Qoder Teams、Qoder CN的差异化定位与能力边界:千问办公主打职场全场景提效,支持自然语言指令一键完成PPT生成、数据分析等高频办公任务;Qoder Teams面向程序员团队,深度整合AI代码生成、团队协同与企业知识库能力;Qoder CN则专为金融、政务等强合规场景打造,实现数据不出境与VPC私有化部署。文章同步给出分场景选型指南与最新活动定价,帮助不同类型的企业按需组合产品,实现业务岗、研发岗与强合规场景的AI能力全覆盖。
3876 5
阿里云千问办公、Qoder Teams、Qoder CN区别与选择指南:模型能力、适用场景与最新活动参考
|
8天前
|
人工智能 自然语言处理 安全
阿里云AI数智鉴密:AI 生成内容如何拿到一张"防篡改的身份证"
隐形水印 + C2PA签名:让AI生成内容“持证上岗”。
1143 0
|
9天前
|
网络协议 Linux iOS开发
【2026实测】Wireshark下载+安装+汉化+使用教程(图文版,巨详细)
Wireshark 是一款免费开源的网络协议分析工具,可实时捕获、解析并可视化数据包,助你诊断网络故障、分析通信协议(如HTTP、DNS、TCP等)。支持Windows/macOS/Linux,含中文界面,新手入门便捷。(239字)
|
3天前
|
缓存 测试技术 API
DeepSeek V4.1 Flash 内测接入:改个模型名即可调用(附代码)
DeepSeek V4.1 Flash 内测不用申请,base_url 不变、改个模型名就能调,9/10 到期。本文讲清接入、计费限流与多模态注意点。
696 0
DeepSeek V4.1 Flash 内测接入:改个模型名即可调用(附代码)
|
10天前
|
缓存 数据可视化 开发工具
DeepSeek Harness 怎么更新?dsh 更新完整指南:更新本体(npx、npm、源码)与更新插件两种方式
DeepSeek Harness 的更新分两层:本体更新(npx 自动最新、npm update -g、源码 git pull)与插件更新(插件市场点更新、命令行覆盖安装)。本文按「准备 → 更新本体 → 更新插件 → 更新后检查」四步走,覆盖新手常见疑问。
1269 1
DeepSeek Harness 怎么更新?dsh 更新完整指南:更新本体(npx、npm、源码)与更新插件两种方式