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

news/2024/11/25 16:35:51/

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 {@Resourceprivate MilvusConfiguration milvusConfiguration;private MilvusServiceClient milvusServiceClient;@PostConstructprivate 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);}@Resourceprivate SeetaModelConfiguration seetaModelConfiguration;private FaceDetectorProxy faceDetectorProxy;private FaceLandmarkerProxy faceLandmarkerProxy;private FaceRecognizerProxy faceRecognizerProxy;private AgePredictorProxy agePredictorProxy;private GenderPredictorProxy genderPredictorProxy;private MaskDetectorProxy maskDetectorProxy;private EyeStateDetectorProxy eyeStateDetectorProxy;}

主类里的初始方法:

    @PostConstructprivate 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]);// 人脸向量特征提取featuresreturn 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.ppmy.cn/news/779458.html

相关文章

进销存管理系统大全【70个进销存系统】

进销存管理系统-精选22 进销存管理系统-精选23 进销存管理系统-精选24 进销存管理系统-精选25 进销存管理系统-精选26 进销存管理系统-精选27 进销存管理系统-精选28 进销存管理系统-精选29 进销存管理系统-精选30 进销存管理系统-精选31 进销存管理系统-精选32 进销存管理系统…

excel 通用进销存(由excel+VBA+MSSQL制作)

说明:此功能由excelVBAMSSQL制作,非excel单一文件.并且支持定时数据备分,支持数据还原操作.若寻excel单一文件制作的进销存的朋友,实在对不起了,我这里真的没有. 功能简述:录入入库单,销售单,可查库存数量,成本,销售利润. 商品入库 商品名称是事先通过"商品档案"表建…

管家婆辉煌版密码遗忘处理

这个很简单&#xff0c;直接进DATA找到SYSDATA.DBF 用EXCEL方式打开把CB项清空保存 然后打开PASSWORD.DBF把F项清除即可

Docker容器与HSM整合的好处

Docker透过容器使创建、部署和运行应用程式变得更加容易。容器允许开发人员可以将一个应用程式与它所需要的所有部分封包&#xff0c;然后将应用程式及其组件作为一个单一的套装软体。 Docker面临的挑战 : ● 遭受特权用户滥用的风险 Docker环境或容器内的权限配置不当可能会导…

怎样修改管家婆服务器密码,管家婆辉煌版如何设置权限和修改操作员密码口令...

为了保证企业财务数据的安全,操作员可在口令权限里设置进入账套的口令,超级用户(系统管理员)可授予操作员不同的操作权限,有效避免操作员越权操作,篡改单据,减少管理员人为操作失误。权限设置有下面几大类:单据使用权限、录账权限、查账权限、其它权限。进入“系统维护-…

管家婆辉煌版7.2版,超级用户密码忘记了

管家婆辉煌版7.2版&#xff0c;超级用户密码忘记了 解决方法&#xff1a; 进管家婆7.2DATA文件夹, 找到SYSDATA.DBF&#xff0c;打开方式用EXCEL&#xff0c;找到CB列,REP_INPUT项, 把数值清除&#xff0c;保存退出。 再找到PASSWORD.DBF&#xff0c;同样用EXCEL方式打开&…

# Linux更换阿里云yum源

Linux更换阿里云yum源 1.进入以下目录 cd /etc/yum.repos.d2.清空目录内容 rm -rf *3.创建文件目录&#xff0c;挂载iso镜像 mkdir /mnt/cdrom mount /dev/cdrom /mnt/cdrom4.创建repo文件&#xff0c;并填充以下内容 vi test.repo[test-server] nametest baseurlfile:///…

【Centos】crontab系统定时配置加载用户环境变量

使用linux系统crontab默认是没有加载用户的环境变量的&#xff0c;所以有些命令是用不了的。 打开任务计划 crontab -e添加环境变量信息 开头加入如下内容&#xff1a; SHELL/bin/bash PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin完整内容示例如下&am…