Java【代码 16】Milvus向量库工具类和SeetaSDK获取人像向量和属性的工具类分享

news2024/9/22 0:20:18

Milvus向量库和SeetaSDK工具类分享

  • 1.Milvus向量库工具类
  • 2.SeetaSDK工具类

1.Milvus向量库工具类

Milvus的Maven依赖:

        <dependency>
            <groupId>io.milvus</groupId>
            <artifactId>milvus-sdk-java</artifactId>
            <version>2.1.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>log4j-slf4j-impl</artifactId>
                    <groupId>org.apache.logging.log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

向量库的配置类:

@Data
@Component
@ConfigurationProperties(MilvusConfiguration.PREFIX)
public class MilvusConfiguration {
    public static final String PREFIX = "milvus-config";

    public String host;
    public int port;
    public String collectionName;

}

工具类主类:

@Slf4j
@Component
public class MilvusUtil {

    @Resource
    private MilvusConfiguration milvusConfiguration;

    private MilvusServiceClient milvusServiceClient;

    @PostConstruct
    private void connectToServer() {
        milvusServiceClient = new MilvusServiceClient(
                ConnectParam.newBuilder()
                        .withHost(milvusConfiguration.host)
                        .withPort(milvusConfiguration.port)
                        .build());
        // 加载数据
        LoadCollectionParam faceSearchNewLoad = LoadCollectionParam.newBuilder()
                .withCollectionName(milvusConfiguration.collectionName).build();
        R<RpcStatus> rpcStatusR = milvusServiceClient.loadCollection(faceSearchNewLoad);
        log.info("Milvus LoadCollection [{}]", rpcStatusR.getStatus() == 0 ? "Successful!" : "Failed!");
    }
}

主类里的数据入库方法:

    public int insertDataToMilvus(String id, String path, float[] feature) {
        List<InsertParam.Field> fields = new ArrayList<>();
        List<Float> featureList = new ArrayList<>(feature.length);
        for (float v : feature) {
            featureList.add(v);
        }
        fields.add(new InsertParam.Field("id", Collections.singletonList(id)));
        fields.add(new InsertParam.Field("image_path", Collections.singletonList(path)));
        fields.add(new InsertParam.Field("image_feature", Collections.singletonList(featureList)));
        InsertParam insertParam = InsertParam.newBuilder()
                .withCollectionName(milvusConfiguration.collectionName)
                //.withPartitionName("novel")
                .withFields(fields)
                .build();
        R<MutationResult> insert = milvusServiceClient.insert(insertParam);
        return insert.getStatus();
    }

主类类的数据查询方法:

  • 这里的topK没有进行参数化。
    public List<MilvusRes> searchImageByFeatureVector(float[] feature) {
        List<Float> featureList = new ArrayList<>(feature.length);
        for (float v : feature) {
            featureList.add(v);
        }
        List<String> queryOutputFields = Arrays.asList("image_path");

        SearchParam faceSearch = SearchParam.newBuilder()
                .withCollectionName(milvusConfiguration.collectionName)
                .withMetricType(MetricType.IP)
                .withVectorFieldName("image_feature")
                .withVectors(Collections.singletonList(featureList))
                .withOutFields(queryOutputFields)
                .withRoundDecimal(3)
                .withTopK(10).build();
        // 执行搜索
        long l = System.currentTimeMillis();
        R<SearchResults> respSearch = milvusServiceClient.search(faceSearch);
        log.info("MilvusServiceClient.search cost [{}]", System.currentTimeMillis() - l);
        // 解析结果数据
        SearchResultData results = respSearch.getData().getResults();
        int scoresCount = results.getScoresCount();
        SearchResultsWrapper wrapperSearch = new SearchResultsWrapper(results);
        List<MilvusRes> milvusResList = new ArrayList<>();
        for (int i = 0; i < scoresCount; i++) {
            float score = wrapperSearch.getIDScore(0).get(i).getScore();
            Object imagePath = wrapperSearch.getFieldData("image_path", 0).get(i);
            MilvusRes milvusRes = MilvusRes.builder().score(score).imagePath(imagePath.toString()).build();
            milvusResList.add(milvusRes);
        }
        return milvusResList;
    }

2.SeetaSDK工具类

SeetaSDK的Maven依赖:

        <dependency>
            <groupId>com.seeta</groupId>
            <artifactId>sdk</artifactId>
            <version>1.2.1</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/seeta-sdk-platform-1.2.1.jar</systemPath>
        </dependency>
       		<!--注意-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                </configuration>
            </plugin>       

jar是从官网下的源码进行的打包:

在这里插入图片描述
工具类主类:

@Slf4j
@Component
public class FaceUtil {

    static {
        // 加载本地方法
        LoadNativeCore.LOAD_NATIVE(SeetaDevice.SEETA_DEVICE_AUTO);
    }

    @Resource
    private SeetaModelConfiguration seetaModelConfiguration;

    private FaceDetectorProxy faceDetectorProxy;
    private FaceLandmarkerProxy faceLandmarkerProxy;
    private FaceRecognizerProxy faceRecognizerProxy;
    private AgePredictorProxy agePredictorProxy;
    private GenderPredictorProxy genderPredictorProxy;
    private MaskDetectorProxy maskDetectorProxy;
    private EyeStateDetectorProxy eyeStateDetectorProxy;

}

主类里的初始方法:

    @PostConstruct
    private void inti() {
        String basePath = seetaModelConfiguration.basePath;
        try {
            // 人脸识别检测器对象池配置
            SeetaConfSetting detectorPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(0, new String[]{basePath + seetaModelConfiguration.faceDetectorModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            faceDetectorProxy = new FaceDetectorProxy(detectorPoolSetting);
            // 关键点定位器【默认使用5点可通过配置切换为68点】
            SeetaConfSetting faceLandmarkerPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(1, new String[]{basePath + seetaModelConfiguration.faceLandmarkerModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            faceLandmarkerProxy = new FaceLandmarkerProxy(faceLandmarkerPoolSetting);
            // 人脸向量特征提取和对比器
            SeetaConfSetting faceRecognizerPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(2, new String[]{basePath + seetaModelConfiguration.faceRecognizerModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            faceRecognizerProxy = new FaceRecognizerProxy(faceRecognizerPoolSetting);
            // 年龄评估器
            SeetaConfSetting agePredictorPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(3, new String[]{basePath + seetaModelConfiguration.agePredictorModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            agePredictorProxy = new AgePredictorProxy(agePredictorPoolSetting);
            // 性别识别器
            SeetaConfSetting genderPredictorPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(4, new String[]{basePath + seetaModelConfiguration.genderPredictorModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            genderPredictorProxy = new GenderPredictorProxy(genderPredictorPoolSetting);
            // 口罩检测器
            SeetaConfSetting maskDetectorPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(5, new String[]{basePath + seetaModelConfiguration.maskDetectorModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            maskDetectorProxy = new MaskDetectorProxy(maskDetectorPoolSetting);
            // 眼睛状态检测
            SeetaConfSetting eyeStaterPoolSetting = new SeetaConfSetting(
                    new SeetaModelSetting(5, new String[]{basePath + seetaModelConfiguration.eyeStateModelFileName},
                            SeetaDevice.SEETA_DEVICE_AUTO));
            eyeStateDetectorProxy = new EyeStateDetectorProxy(eyeStaterPoolSetting);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

主类里的根据图片路径获取脸部特征向量方法:

    /**
     * 根据图片路径获取脸部特征向量
     *
     * @param imagePath 图片路径
     * @return 脸部特征向量
     */
    public float[] getFaceFeaturesByPath(String imagePath) {
        try {
            // 照片人脸识别
            SeetaImageData image = SeetafaceUtil.toSeetaImageData(imagePath);
            SeetaRect[] detects = faceDetectorProxy.detect(image);
            // 人脸关键点定位【主驾或副驾仅有一个人脸,多个人脸仅取第一个】
            if (detects.length > 0) {
                SeetaPointF[] pointFace = faceLandmarkerProxy.mark(image, detects[0]);
                // 人脸向量特征提取features
                return faceRecognizerProxy.extract(image, pointFace);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

主类里的根据人像图片的路径获取其属性【年龄、性别、是否戴口罩、眼睛状态】方法:

    /**
     * 根据人像图片的路径获取其属性【年龄、性别、是否戴口罩、眼睛状态】
     *
     * @param imagePath 图片路径
     * @return 图片属性 MAP 对象
     */
    public Map<String, Object> getAttributeByPath(String imagePath) {
        long l = System.currentTimeMillis();
        Map<String, Object> attributeMap = new HashMap<>(4);
        try {
            // 监测人脸
            SeetaImageData image = SeetafaceUtil.toSeetaImageData(imagePath);
            SeetaRect[] detects = faceDetectorProxy.detect(image);
            if (detects.length > 0) {
                SeetaPointF[] pointFace = faceLandmarkerProxy.mark(image, detects[0]);
                // 获取年龄
                int age = agePredictorProxy.predictAgeWithCrop(image, pointFace);
                attributeMap.put("age", age);
                // 性别
                GenderPredictor.GENDER gender = genderPredictorProxy.predictGenderWithCrop(image, pointFace).getGender();
                attributeMap.put("gender", gender);
                // 口罩
                boolean mask = maskDetectorProxy.detect(image, detects[0]).getMask();
                attributeMap.put("mask", mask);
                // 眼睛
                EyeStateDetector.EYE_STATE[] eyeStates = eyeStateDetectorProxy.detect(image, pointFace);
                attributeMap.put("eye", Arrays.toString(eyeStates));
                log.info("getAttributeByPath [{}] cost [{}]", imagePath, System.currentTimeMillis() - l);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return attributeMap;
        }
        return attributeMap;
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/729185.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

利用Ettercap进行钓鱼攻击

原理:利用ARP协议特性,使用ettercap在内网不断的发送和抢答MAC地址,让受害者访问网关及DNS服务器实际均为攻击者的服务器。 前言&#xff1a;Ettercap是一款流行的网络安全工具&#xff0c;可用于网络嗅探、欺骗和分析攻击。它可以截获网络流量&#xff0c;使用户可以查看到传输…

Sql Injection — 注入攻击原理-2(实战)

还是实战&#xff0c;如果没什么事的话几乎每天日更 目录 前言一、总结 前言 sql实战-2 提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 一、 公司的新闻网 我们进入一篇文章&#xff0c;我们发现这个网页应该是ASP动态网页文件 还记得第一篇文章的sq…

了解O2OA(翱途)开发平台中的VIP应用

使用O2OA(翱途)开发平台可以非常方便地进行项目的业务需求开发与实施&#xff0c;O2OA(翱途)开发平台并不限制实现的系统类型&#xff0c;所以能实现的系统很多&#xff0c;最终呈现的项目成果也是多样性的&#xff0c;可能是OA系统&#xff0c;可能是人力资源管理系统&#xf…

JVM进阶学习(类加载器、垃圾回收、JVM调优、内存泄漏的排查思路)

文章目录 1、JVM组成1.1、JVM组成及运行流程1.2、程序计数器什么是程序计数器&#xff1f; 1.3、Java堆你能给我详细的介绍Java堆吗? 1.4、虚拟机栈什么是虚拟机栈垃圾回收是否涉及栈内存&#xff1f;栈内存分配越大越好吗&#xff1f;方法内的局部变量是否线程安全&#xff1…

蓝桥杯专题-真题版含答案-【啤酒和饮料】【六角填数】【兰顿蚂蚁】【猜字母】

点击跳转专栏>Unity3D特效百例点击跳转专栏>案例项目实战源码点击跳转专栏>游戏脚本-辅助自动化点击跳转专栏>Android控件全解手册点击跳转专栏>Scratch编程案例点击跳转>软考全系列点击跳转>蓝桥系列 &#x1f449;关于作者 专注于Android/Unity和各种游…

功能测评-InsCode Stable Diffusion 美图活动一期

一、 Stable Diffusion 模型在线使用地址&#xff1a; https://inscode.csdn.net/inscode/Stable-Diffusion 进入之后点击运行并使用&#xff0c;会弹出一个购买算力资源的窗口。由于是试用&#xff0c;不涉及到连续生成多张图片等场合&#xff0c;因此算力足够用了&#xff…

如何将idea里面的项目上传到gitee仓库里面?

目录 第一步&#xff0c;在Gitee这边新建一个仓库 第二步&#xff0c;添加ssh公钥 第三步&#xff0c;将idea上面的项目上传到仓库。 第四步&#xff0c;刷新gitee这边的网页就可以看到我们上传的项目了哦。 总结 本篇文章是用来记录我是如何将idea上面的项目上传到gitee仓库…

如何使用ChatGPT的API(三)处理违规输入

当我们要构建一个对话机器人的时候&#xff0c;常常需要检测用户的输入是否有违规。用户是否输入了一些暴力&#xff0c;色情的内容&#xff0c;这对维护系统正规使用至关重要。下面将介绍一些方法来检测用户的输入是否违规。 OpenAI Moderation API OpenAI 提供了免费的Mode…

亚马逊摊上事了,欧盟委员会对其收购iRobot展开反垄断调查

KlipC报道&#xff1a;周四亚马逊16.5亿美元收购扫地机器人制造商iRobot的交易引发欧盟深入调查&#xff0c;消息公布后&#xff0c;iRobot股价没有太大变动&#xff0c;然而截至当日收盘&#xff0c;亚马逊跌1.55%&#xff0c;报128.36美元。 对此欧盟表示&#xff1a;“亚马逊…

Dijkstra求最短路 — 朴素/堆优化 + 模拟邻接表 及 遍历

Dijkstra求最短路 给定一个 n个点 m 条边的有向图&#xff0c;图中可能存在重边和自环&#xff0c;所有边权均为正值。请你求出 1号点到 n 号点的最短距离&#xff0c;如果无法从 1 号点走到 n 号点&#xff0c;则输出 −1。 朴素dijkstra #include<iostream> #include&…

PTA——L1-027 出租分数 20

下面是新浪微博上曾经很火的一张图&#xff1a; 一时间网上一片求救声&#xff0c;急问这个怎么破。其实这段代码很简单&#xff0c;index数组就是arr数组的下标&#xff0c;index[0]2 对应 arr[2]1&#xff0c;index[1]0 对应 arr[0]8&#xff0c;index[2]3 对应 arr[3]0&…

路径规划算法:基于寄生捕食优化的路径规划算法- 附代码

路径规划算法&#xff1a;基于寄生捕食优化的路径规划算法- 附代码 文章目录 路径规划算法&#xff1a;基于寄生捕食优化的路径规划算法- 附代码1.算法原理1.1 环境设定1.2 约束条件1.3 适应度函数 2.算法结果3.MATLAB代码4.参考文献 摘要&#xff1a;本文主要介绍利用智能优化…

【Java基础教程】(五)程序概念篇 · 下:夯实基础!全面解析Java程序的逻辑控制体:顺序、选择与循环结构~

Java基础教程之程序概念 下 本节学习目标1️⃣ 程序逻辑控制1.1 顺序结构1.2 分支结构1.2.1 if 选择结构1.2.2 switch 选择结构 1.3 循环结构1.3.1 while 循环1.3.2 for 循环1.3.3 循环控制 &#x1f33e; 总结 本节学习目标 掌握Java中分支结构、循环结构、循环控制语法的使…

前端js代码一句话模拟Ctrl+A全选网页内容效果document.execCommand(‘selectAll‘);

document.execCommand(selectAll);//命令不区分大小写 document.execCommand(aCommandName, aShowDefaultUI, aValueArgument) aCommandName&#xff1a;命令名称 aShowDefaultUI&#xff1a;交互方式&#xff0c; Boolean值&#xff0c;true的话将显示对话框&#xff0c;如…

Oracle11g 64位下载

下载地址 http://download.oracle.com/otn/linux/oracle11g/R2/linux.x64_11gR2_database_1of2.ziphttp://download.oracle.com/otn/linux/oracle11g/R2/linux.x64_11gR2_database_2of2.zip如果下载出现如下错误页面 这时候可以登录oracle官网&#xff0c;随意点击一个下载&am…

基于qrencode实现linux打印二维码

一、概述 在Centos 7环境的控制台打印二维码。 二、实现方式 1.安装qrencode工具 sudo yum install -y qrencode 2.命令 echo "你的字符串" | qrencode -t UTF8三、展示

山海鲸Cesium:帮你用更简单的方式升级视效

CesiumJS作为绝大多数人都在用的开源地球可视化引擎&#xff0c;视觉效果并不拔尖&#xff0c;这让很多giser都想着有一天升级一下视效&#xff0c;从众多平庸的项目中脱颖而出。然而&#xff0c;对于一些使用Cesium的项目来说&#xff0c;要想达到Cesium for unreal的视觉效果…

2023年智能制造与自动化前沿国际会议 | Ei Scopus双检索

会议简介 Brief Introduction 2023年智能制造与自动化前沿国际会议&#xff08;CFIMA 2023&#xff09; 会议时间&#xff1a;2023年11月3 -5日 召开地点&#xff1a;中国天津 大会官网&#xff1a;www.cfima.org 随着全球新一轮科技革命和产业变革突飞猛进&#xff0c;新一代信…

100天精通Golang(基础入门篇)——第15天:深入解析Go语言中函数的应用:从基础到进阶,助您精通函数编程!(进阶)

&#x1f337; 博主 libin9iOak带您 Go to Golang Language.✨ &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &#x1f30a; 《I…

论文学习——U-Net: Convolutional Networks for Biomedical Image Segmentation

UNet的特点 采用端到端的结构&#xff0c;通过FCN&#xff08;最后一层仍然是通过卷积完成&#xff09;&#xff0c;最后输出图像。通过编码&#xff08;下采样&#xff09;-解码&#xff08;上采样&#xff09;形成一个“U”型结构。每次下采样时&#xff0c;先进行两次卷积&…