IT评测·应用市场-qidao123.com

标题: JavaCV的摄像头实战之十二:性别检测 [打印本页]

作者: 熊熊出没    时间: 2023-7-1 06:18
标题: JavaCV的摄像头实战之十二:性别检测
欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos
本篇概览

关于性别和年龄检测

源码下载

名称链接备注项目主页https://github.com/zq2599/blog_demos该项目在GitHub上的主页git仓库地址(https)https://github.com/zq2599/blog_demos.git该项目源码的仓库地址,https协议git仓库地址(ssh)git@github.com:zq2599/blog_demos.git该项目源码的仓库地址,ssh协议
准备:文件下载


准备:代码接口简介


编码:主程序

  1. protected CanvasFrame previewCanvas
复制代码
  1.     /**
  2.      * 检测工具接口
  3.      */
  4.     private DetectService detectService;
复制代码
  1.     /**
  2.      * 不同的检测工具,可以通过构造方法传入
  3.      * @param detectService
  4.      */
  5.     public PreviewCameraWithGenderAge(DetectService detectService) {
  6.         this.detectService = detectService;
  7.     }
复制代码
  1.     @Override
  2.     protected void initOutput() throws Exception {
  3.         previewCanvas = new CanvasFrame("摄像头预览", CanvasFrame.getDefaultGamma() / grabber.getGamma());
  4.         previewCanvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  5.         previewCanvas.setAlwaysOnTop(true);
  6.         // 检测服务的初始化操作
  7.         detectService.init();
  8.     }
复制代码
  1.     @Override
  2.     protected void output(Frame frame) {
  3.         // 原始帧先交给检测服务处理,这个处理包括物体检测,再将检测结果标注在原始图片上,
  4.         // 然后转换为帧返回
  5.         Frame detectedFrame = detectService.convert(frame);
  6.         // 预览窗口上显示的帧是标注了检测结果的帧
  7.         previewCanvas.showImage(detectedFrame);
  8.     }
复制代码
  1.     @Override
  2.     protected void releaseOutputResource() {
  3.         if (null!= previewCanvas) {
  4.             previewCanvas.dispose();
  5.         }
  6.         // 检测工具也要释放资源
  7.         detectService.releaseOutputResource();
  8.     }
复制代码
  1.     @Override
  2.     protected int getInterval() {
  3.         return super.getInterval()/8;
  4.     }
复制代码
  1.     public static void main(String[] args) {
  2.         String base = "E:\\temp\\202112\\25\\opencv\";
  3.   
  4.         DetectService detectService = new GenderDetectService(
  5.                 base + "haarcascade_frontalface_alt.xml",
  6.                 base + "gender\\deploy.prototxt",
  7.                 base + "gender\\gender_net.caffemodel");
  8.                
  9.         new PreviewCameraWithGenderAge(detectService).action(1000);
  10.     }
复制代码
编码:服务接口回顾

  1. package com.bolingcavalry.grabpush.extend;
  2. public interface DetectService {
  3.     /**
  4.      * 根据传入的MAT构造相同尺寸的MAT,存放灰度图片用于以后的检测
  5.      * @param src 原始图片的MAT对象
  6.      * @return 相同尺寸的灰度图片的MAT对象
  7.      */
  8.     static Mat buildGrayImage(Mat src) {
  9.         return new Mat(src.rows(), src.cols(), CV_8UC1);
  10.     }
  11.    
  12.     /**
  13.      * 初始化操作,例如模型下载
  14.      * @throws Exception
  15.      */
  16.     void init() throws Exception;
  17.     /**
  18.      * 得到原始帧,做识别,添加框选
  19.      * @param frame
  20.      * @return
  21.      */
  22.     Frame convert(Frame frame);
  23.     /**
  24.      * 释放资源
  25.      */
  26.     void releaseOutputResource();
  27. }
复制代码
编码:检测服务实现

  1. package com.bolingcavalry.grabpush.extend;
  2. import com.bolingcavalry.grabpush.Constants;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.bytedeco.javacpp.indexer.Indexer;
  5. import org.bytedeco.javacv.Frame;
  6. import org.bytedeco.javacv.OpenCVFrameConverter;
  7. import org.bytedeco.opencv.opencv_core.*;
  8. import org.bytedeco.opencv.opencv_dnn.Net;
  9. import org.bytedeco.opencv.opencv_objdetect.CascadeClassifier;
  10. import static org.bytedeco.opencv.global.opencv_core.NORM_MINMAX;
  11. import static org.bytedeco.opencv.global.opencv_core.normalize;
  12. import static org.bytedeco.opencv.global.opencv_dnn.blobFromImage;
  13. import static org.bytedeco.opencv.global.opencv_dnn.readNetFromCaffe;
  14. import static org.bytedeco.opencv.global.opencv_imgproc.*;
  15. /**
  16. * @author willzhao
  17. * @version 1.0
  18. * @description 音频相关的服务
  19. * @date 2021/12/3 8:09
  20. */
  21. @Slf4j
  22. public class GenderDetectService implements DetectService {
  23.     /**
  24.      * 每一帧原始图片的对象
  25.      */
  26.     private Mat grabbedImage = null;
  27.     /**
  28.      * 原始图片对应的灰度图片对象
  29.      */
  30.     private Mat grayImage = null;
  31.     /**
  32.      * 分类器
  33.      */
  34.     private CascadeClassifier classifier;
  35.     /**
  36.      * 转换器
  37.      */
  38.     private OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
  39.     /**
  40.      * 人脸检测模型文件的下载地址
  41.      */
  42.     private String classifierModelFilePath;
  43.     /**
  44.      * 性别识别proto文件的下载地址
  45.      */
  46.     private String genderProtoFilePath;
  47.     /**
  48.      * 性别识别模型文件的下载地址
  49.      */
  50.     private String genderModelFilePath;
  51.     /**
  52.      * 推理性别的神经网络对象
  53.      */
  54.     private Net cnnNet;
  55.     /**
  56.      * 构造方法,在此指定proto和模型文件的下载地址
  57.      * @param classifierModelFilePath
  58.      * @param cnnProtoFilePath
  59.      * @param cnnModelFilePath
  60.      */
  61.     public GenderDetectService(String classifierModelFilePath,
  62.                                String cnnProtoFilePath,
  63.                                String cnnModelFilePath) {
  64.         this.classifierModelFilePath = classifierModelFilePath;
  65.         this.genderProtoFilePath = cnnProtoFilePath;
  66.         this.genderModelFilePath = cnnModelFilePath;
  67.     }
  68.     /**
  69.      * 初始化操作,主要是创建推理用的神经网络
  70.      * @throws Exception
  71.      */
  72.     @Override
  73.     public void init() throws Exception {
  74.         // 根据模型文件实例化分类器
  75.         classifier = new CascadeClassifier(classifierModelFilePath);
  76.         // 实例化推理性别的神经网络
  77.         cnnNet = readNetFromCaffe(genderProtoFilePath, genderModelFilePath);
  78.     }
  79.     @Override
  80.     public Frame convert(Frame frame) {
  81.         // 由帧转为Mat
  82.         grabbedImage = converter.convert(frame);
  83.         // 灰度Mat,用于检测
  84.         if (null==grayImage) {
  85.             grayImage = DetectService.buildGrayImage(grabbedImage);
  86.         }
  87.         // 当前图片转为灰度图片
  88.         cvtColor(grabbedImage, grayImage, CV_BGR2GRAY);
  89.         // 存放检测结果的容器
  90.         RectVector objects = new RectVector();
  91.         // 开始检测
  92.         classifier.detectMultiScale(grayImage, objects);
  93.         // 检测结果总数
  94.         long total = objects.size();
  95.         // 如果没有检测到结果,就用原始帧返回
  96.         if (total<1) {
  97.             return frame;
  98.         }
  99.         int pos_x;
  100.         int pos_y;
  101.         Mat faceMat;
  102.         //推理时的入参
  103.         Mat inputBlob;
  104.         // 推理结果
  105.         Mat prob;
  106.         // 如果有检测结果,就根据结果的数据构造矩形框,画在原图上
  107.         for (long i = 0; i < total; i++) {
  108.             Rect r = objects.get(i);
  109.             // 人脸对应的Mat实例(注意:要用彩图,不能用灰度图!!!)
  110.             faceMat = new Mat(grabbedImage, r);
  111.             // 缩放到神经网络所需的尺寸
  112.             resize(faceMat, faceMat, new Size(Constants.CNN_PREIDICT_IMG_WIDTH, Constants.CNN_PREIDICT_IMG_HEIGHT));
  113.             // 归一化
  114.             normalize(faceMat, faceMat, 0, Math.pow(2, frame.imageDepth), NORM_MINMAX, -1, null);
  115.             // 转为推理时所需的的blob类型
  116.             inputBlob = blobFromImage(faceMat);
  117.             // 为神经网络设置入参
  118.             cnnNet.setInput(inputBlob, "data", 1.0, null);      //set the network input
  119.             // 推理
  120.             prob = cnnNet.forward("prob");
  121.             // 根据推理结果得到在人脸上标注的内容
  122.             String lable = getDescriptionFromPredictResult(prob);
  123.             // 人脸标注的横坐标
  124.             pos_x = Math.max(r.tl().x()-10, 0);
  125.             // 人脸标注的纵坐标
  126.             pos_y = Math.max(r.tl().y()-10, 0);
  127.             // 给人脸做标注,标注性别
  128.             putText(grabbedImage, lable, new Point(pos_x, pos_y), FONT_HERSHEY_PLAIN, 1.5, new Scalar(0,255,0,2.0));
  129.             // 给人脸加边框时的边框位置
  130.             int x = r.x(), y = r.y(), w = r.width(), h = r.height();
  131.             // 给人脸加边框
  132.             rectangle(grabbedImage, new Point(x, y), new Point(x + w, y + h), Scalar.RED, 1, CV_AA, 0);
  133.         }
  134.         // 释放检测结果资源
  135.         objects.close();
  136.         // 将标注过的图片转为帧,返回
  137.         return converter.convert(grabbedImage);
  138.     }
  139.     /**
  140.      * 程序结束前,释放人脸识别的资源
  141.      */
  142.     @Override
  143.     public void releaseOutputResource() {
  144.         if (null!=grabbedImage) {
  145.             grabbedImage.release();
  146.         }
  147.         if (null!=grayImage) {
  148.             grayImage.release();
  149.         }
  150.         if (null!=classifier) {
  151.             classifier.close();
  152.         }
  153.         if (null!= cnnNet) {
  154.             cnnNet.close();
  155.         }
  156.     }
  157.     /**
  158.      * 根据推理结果得到在头像上要标注的内容
  159.      * @param prob
  160.      * @return
  161.      */
  162.     protected String getDescriptionFromPredictResult(Mat prob) {
  163.         Indexer indexer = prob.createIndexer();
  164.         // 比较两种性别的概率,概率大的作为当前头像的性别
  165.         return indexer.getDouble(0,0) > indexer.getDouble(0,1)
  166.                ? "male"
  167.                : "female";
  168.     }
  169. }
复制代码

验证

欢迎关注博客园:程序员欣宸

学习路上,你不孤单,欣宸原创一路相伴...

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4