精华内容
下载资源
问答
  • java opencv识别by Manish Bansal 通过Manish Bansal 在Java中使用OpenCV进行面部识别 (Facial recognition using OpenCV in Java) Ever since the Artificial Intelligence boom began — or the iPhone X ...

    java opencv识别

    by Manish Bansal

    通过Manish Bansal

    在Java中使用OpenCV进行面部识别 (Facial recognition using OpenCV in Java)

    Ever since the Artificial Intelligence boom began — or the iPhone X advertisement featuring the face unlock feature hit TV screens — I’ve wanted to try this technology. However, once I started googling about it, I typically only found code examples in Python. And being a Java enthusiast for seven years, I got demotivated seeing that. Therefore, I finally decided to hunt for Java open source libraries for this.

    自从人工智能热潮开始-或具有面部解锁功能的iPhone X广告投放电视屏幕以来-我一直想尝试这种技术。 但是,一旦开始搜索它,我通常只会在Python中找到代码示例。 成为Java爱好者已有7年了,对此我感到无比激动。 因此,我最终决定为此寻找Java开源库。

    Currently, there are various Java libraries out there. But the most popular one I found was OpenCV.

    当前,有各种Java库。 但是我发现最受欢迎的是OpenCV

    OpenCV is an open source computer vision library that has tons of modules like object detection, face recognition, and augmented reality. Although this library is written in C++, it also offers battle-tested Java bindings.

    OpenCV是一个开放源代码的计算机视觉库,具有大量的模块,例如对象检测,面部识别和增强现实。 尽管该库是用C ++编写的,但它也提供了经过实践检验的Java绑定。

    However, there is one issue. As part of its software release, it offers only a few modules (with Java bindings) out of the box — and facial recognition is not one of them. Therefore, to use it, you need to manually build it.

    但是,有一个问题。 作为其软件版本的一部分,它仅提供了一些现成的模块(带有Java绑定),而面部识别并不是其中之一。 因此,要使用它,您需要手动构建它。

    Wait! What? Why?

    等待! 什么? 为什么?

    Yes — the reason cited by the OpenCV community is that the modules are not completely stable. Therefore, they are not bundled along with the standard release. Hence, they maintain them in a separate repository here.

    是的-OpenCV社区引用的原因是模块并不完全稳定。 因此,它们未与标准版本捆绑在一起。 因此,他们将它们维护在此处的单独存储库中。

    If you have no or very little C++ experience (like me), you must have already started to feel dizzy about building a C++ library yourself. But don’t worry, I am here to hold your hand and walk you through this tedious process. So let’s begin, shall we?

    如果您没有或只有很少的C ++经验(像我一样),那么您一定已经开始对自己构建C ++库感到头晕。 但是不用担心,我在这里牵着你的手,引导您完成这个繁琐的过程。 那么,让我们开始吧?

    从零开始为Java构建OpenCV (Building OpenCV for Java from scratch)

    You can find various resources for step by step instructions like this, this, and this. However, none of them worked perfectly for me, as one thing or another was missing. The closest I found, which helped me, is this one. However, you do not need to refer to it. You can follow below steps and you will be good.

    您可以找到各种资源,以获取有关步骤的逐步说明。 但是,它们都不适合我,因为缺少一件事或另一件事。 这让我我发现的最接近,是一个。 但是,您无需引用它。 您可以按照以下步骤操作,这会很好。

    First, you need to have the below software on your PC. Here, I am building a 64-bit version of the library as I own a 64 bit PC. But you can build it for 32-bit as well.

    首先,您需要在计算机上安装以下软件。 在这里,我拥有一台64位PC,因此正在构建该库的64位版本。 但是您也可以将其构建为32位。

    The required software is:

    所需的软件是:

    1. Cmake (I used 3.6.0 rc-4 version).

      Cmake (我使用的是3.6.0 rc-4版本)。

    2. Ant (used internally for building JAR)

      蚂蚁 (内部用于构建JAR)

    3. MinGW — W64 GCC-8.1.0

      MinGW — W64 GCC-8.1.0
    4. 64 bit JDK 1.8

      64位JDK 1.8

    A word about MinGW: Here, to build this library, we need C++ compilers. You can use Visual Studio tools (VS), which is far better. However, I did not have the luxury to do that, as I built it on my office laptop and VS is licensed software unavailable to Java people here. Therefore, I had to use open source tools, and the best one is MinGW (Minimalist GNU for Windows).

    关于MinGW的一点说明:在这里,要构建此库,我们需要C ++编译器。 您可以使用Visual Studio工具(VS),这要好得多。 但是,我没有这样做的奢侈,因为我是在办公室笔记本电脑上构建它的,而VS是这里的Java人员无法获得的许可软件。 因此,我不得不使用开源工具,最好的一种是MinGW(Windows的极简主义GNU)。

    Also, it is very important to use the correct version of MinGW. Download version x86_64-posix-seh, as there is thread support in this version. I have not tried all other versions. But version x86_64-win32-sjlj does not work at all.

    同样,使用正确版本的MinGW也非常重要。 下载版本x86_64-posix-seh ,因为此版本中有线程支持。 我还没有尝试所有其他版本。 但是版本x86_64-win32-sjlj根本不起作用。

    To give some more perspective, the build is done by the utility called make which comes as part of MinGW (bin/mingw32-make.exe). make is a task runner for C++ like “Ant” is for Java. But C++ code and make scripts are very much platform-dependent. Hence, to make the distributables platform-independent, the utility CMake is used. CMake generates platform-dependent make scripts.

    为了提供更多的视角,该构建由名为make的实用程序完成,该实用程序是MinGW的一部分(bin / mingw32-make.exe)。 make是C ++的任务运行程序,例如“ Ant”是Java的。 但是C ++代码和make脚本在很大程度上取决于平台。 因此,为了使可分发内容独立于平台,使用了实用工具CMake 。 CMake生成依赖于平台的make脚本。

    使用CMake生成构建配置 (Generating build configurations using CMake)

    Step 1: Download the source code zip of both the opencv and opencv_contrib, and extract them into a directory. Further, create a folder called “build” in the same directory (I created “build_posix” as visible in the screenshots).

    步骤1:下载opencvopencv_contrib的源代码zip,并将它们压缩到目录中。 此外,在同一目录中创建一个名为“ build”的文件夹(我在屏幕快照中创建了“ build_posix”)。

    Step 2: Open CMake. Point “where is the source code” to the opencv extracted folder. Further, point “where to build the binaries” to the “build” folder you created.

    步骤2:打开CMake。 将“源代码在哪里”指向opencv提取的文件夹。 此外,将“在哪里生成二进制文件”指向您创建的“ build”文件夹。

    Step 3: Add the 64 bit JDK 1.8 bin folder, the MinGW bin folder, and the Ant bin folder to the “PATH” environment variables. This is important, as CMake will look in the environment variables for configuration. If this is not done, then we will have to configure CMake manually in step 5.

    步骤3:将64位JDK 1.8 bin文件夹,MinGW bin文件夹和Ant bin文件夹添加到“ PATH”环境变量。 这很重要,因为CMake会在环境变量中进行配置。 如果不这样做,那么我们将必须在步骤5中手动配置CMake。

    In case you have multiple JDKs in your system and you already have some different JDK in “PATH” & you don’t want to add JDK 1.8 in “PATH”, you can skip this. But do configure it manually in step 5.

    如果您的系统中有多个JDK,并且“ PATH”中已经有其他JDK,并且您不想在“ PATH”中添加JDK 1.8,则可以跳过此步骤。 但是请在步骤5中手动进行配置。

    Step 4: Press the “Configure” button and select “ MinGw Makefiles” and “finish”. After this, CMake will start configuring your project. It will take a while and, after it finishes configuring, it will show the current available configurations.

    步骤4:按“配置”按钮,然后选择“ MinGw Makefiles”和“ finish”。 之后,CMake将开始配置您的项目。 这将需要一段时间,并且在完成配置后将显示当前可用的配置。

    In case you are wondering if the configurations generated for you are correct, you can refer to the logs which got generated for me here and compare.

    如果您想知道为您生成的配置是否正确,可以在这里参考为我生成的日志并进行比较。

    Step 5: Now comes the most important part — changing the configurations. First, click the checkboxes “Grouped” and “Advanced” to organize the configurations.

    步骤5:现在是最重要的部分-更改配置。 首先,单击“分组”和“高级”复选框以组织配置。

    • Verify that ANT_EXECUTABLE (search “ANT_EXECUTABLE” in the search box) and all five “JAVA” configurations are pointing to the 64-bit JDK 1.8. If Step 3 was done properly, then this will be correct. Otherwise, correct them.

      验证ANT_EXECUTABLE(在搜索框中搜索“ ANT_EXECUTABLE”)和所有五个“ JAVA”配置都指向64位JDK 1.8。 如果步骤3正确完成,那么这将是正确的。 否则,请更正它们。
    • Un-check Python (search “Python”) related check boxes under “BUILD” and “INSTALL” groups as we don’t need Python builds.

      取消选中“构建”和“安装”组下与Python相关的复选框(搜索“ Python”),因为我们不需要Python版本。
    • Disable “WITH_MSMF” and “WITH_IPP & WITH_TBB”. These libs are only available for VS.

      禁用“ WITH_MSMF”和“ WITH_IPP&WITH_TBB”。 这些库仅适用于VS。
    • Edit “OPENCV_EXTRA_MODULES_PATH” under “OPENCV” group and set it to the “modules” folder under the “opencv_contrib” source folder you extracted earlier.

      编辑“ OPENCV”组下的“ OPENCV_EXTRA_MODULES_PATH”,并将其设置为先前提取的“ opencv_contrib”源文件夹下的“ modules”文件夹。

    After this, press the “Configure” button again. This will do the final configurations. You can refer to the logs which got generated for me here.

    之后,再次按“配置”按钮。 这将完成最终配置。 您可以在这里参考为我生成的日志。

    Note: Make sure to compare your “Configure” logs generated with the one I shared in pastebin above. If you find some major difference, then first try correcting your configurations and press “Configure” again. Otherwise, there are chances that your build will fail and that it will be more difficult to debug.

    注意 :请确保将生成的“配置”日志与我上面在pastebin中共享的日志进行比较。 如果发现主要差异,请首先尝试更正配置,然后再次按“配置”。 否则,您的构建可能会失败,并且调试起来会更加困难。

    Step 6: After this, press “Generate”. It will take few seconds and then close CMake.

    步骤6:在此之后,按“生成”。 这将需要几秒钟,然后关闭CMake。

    编译OpenCV (Compiling OpenCV)

    Now, if all the configurations generated above are correct, this task will be a breeze (of 2–3 hours!). Just open the command prompt, go to the “build” folder, and execute the command below.

    现在,如果上面生成的所有配置都是正确的,那么此任务将变得轻而易举(2-3小时!)。 只需打开命令提示符,转到“ build”文件夹,然后执行以下命令即可。

    mingw32-make.exe  -j5 > buildLogs.txt

    Here, -j5 is added, which instructs the make utility to run five jobs in parallel. This will make your build faster, at least theoretically.

    在这里,添加了-j5 ,它指示make实用程序并行运行五个作业。 至少从理论上讲,这将使您的构建速度更快。

    Further, do not forget to push the logs to a text file. These might get too big, in which case your command prompt window might truncate it. You need them in case compilation fails. You can refer to the compilation logs generated in my case here.

    此外,不要忘记将日志推送到文本文件。 它们可能太大,在这种情况下,命令提示符窗口可能会截断它。 如果编译失败,则需要它们。 您可以在此处参考以我的情况生成的编译日志。

    Note: The order of log statements might not be the same for you, as the build is happening in five parallel threads.

    :由于构建是在五个并行线程中进行的,因此日志语句的顺序可能与您不同。

    Once the build is over, you can check the “bin” and “lib” folders inside your “build” directory. Inside “bin”, you will have all your opencv*.exe’s and libopencv*.dll’s and your compiled JAR. Further, “lib” will have your main dll (libopencv_javaxxx.dll) along with some more dependent files.

    构建完成后,您可以检查“ build”目录中的“ bin”和“ lib”文件夹。 在“ bin”中,您将拥有所有的opencv * .exe和libopencv * .dll以及已编译的JAR。 此外,“ lib”将具有您的主dll(libopencv_javaxxx.dll)以及一些其他相关文件。

    使用OpenCV人脸识别API (Hands on with OpenCV face recognition API)

    Now that you have built the library, you first need to set up the environment variables, as well as the user library, in Eclipse.

    既然已经构建了库,则首先需要在Eclipse中设置环境变量以及用户库。

    1. Create a variable OPENCV_JAVA_BIN and point it to the “bin” folder generated inside your “build” directory.

      创建一个变量OPENCV_JAVA_BIN并将其指向在“ build”目录内生成的“ bin”文件夹。
    2. Create OPENCV_JAVA_LIB and point it to the “lib” folder generated inside your “build” directory.

      创建OPENCV_JAVA_LIB并将其指向在“ build”目录内生成的“ lib”文件夹。
    3. Append both the above variables to the “PATH” variable.

      将以上两个变量附加到“ PATH”变量。
    4. Open up your Eclipse and create a new user library which you will be using for your face recognition project. Go to “Window” > “Preferences”. From the menu, navigate under “Java” > “Build Path” > “User Libraries” and choose “New…” . Enter a name for the library — for example, opencv — and select the newly created user library. Choose “Add External JARs…” , and browse to select “opencv-3xx.jar” from your computer.

      打开Eclipse并创建一个新的用户库,该库将用于人脸识别项目。 进入“窗口”>“Preferenc ES”。 从菜单中,导航至“ Java”>“构建路径”>“用户库”,然后选择“新建...”。 输入库的名称,例如opencv,然后选择新创建的用户库。 选择“添加外部JAR ...”,然后浏览以从计算机中选择“ opencv-3xx.jar”。

    After this, there is no need to link the native library, as this was added to your “path” variables in Step 3.

    此后, 无需链接本机库,因为它已在步骤3中添加到“ path”变量中。

    Once you are done with this setup, you can clone my Git repository from here and import the project into your Eclipse workspace. Further, you will need to add JDK 1.8 as well as the opencv user library (just created above) to this project. Once you are done, you will be ready to test your newly built OpenCV library.

    完成此设置后,您可以从此处克隆我的Git存储库并将项目导入到Eclipse工作区中。 此外,您将需要向该项目中添加JDK 1.8以及opencv用户库(如上所述)。 完成后,就可以测试新构建的OpenCV库了。

    As of this writing, there are three programs in this project.

    在撰写本文时,该项目中包含三个程序。

    • HelloWorld: you can run this to test if your OpenCV library setup is ok. If this does not work properly, you need to sort this out first. The only issues you will encounter at this point will be related to system environment variables or user library setup.

      HelloWorld :您可以运行它来测试您的OpenCV库设置是否正确。 如果不能正常工作,你必须解决了这一点。 此时您将遇到的唯一问题与系统环境变量或用户库设置有关。

    • FaceDetection: you can use this to test the face detection module. It is a different module from face recognition. This is a module which gets shipped along with standard release of OpenCV. As of this writing, we can provide an image as an input to the program, and it will detect all the faces inside the image. The output image has green rectangles drawn on all the detected faces.

      FaceDetection :您可以使用它来测试面部检测模块。 它是与人脸识别不同的模块。 这是随标准版本的OpenCV一起提供的模块。 在撰写本文时,我们可以提供图像作为程序的输入,它将检测图像中的所有面部。 输出图像在所有检测到的面部上绘制了绿色矩形。

    • FaceRecognition: the OpenCV facerec module includes three algorithms:

      FaceRecognition: OpenCV facerec模块包含三种算法:

    1. Eigenfaces

      特征脸
    2. Fisherfaces

      渔人脸
    3. Local Binary Patterns Histograms.

      本地二进制模式直方图。

    For technical details on all these algorithms, you can refer this official article. For demonstration purposes, I will show you how to use the Eigenfaces algorithm.

    有关所有这些算法的技术详细信息,请参阅官方文章。 出于演示目的,我将向您展示如何使用Eigenfaces算法。

    First, you need to download training data from the face database. This data contains ten different images for each of 40 distinct subjects (400 images). For some subjects, the images were taken at different times, varying the lighting, facial expressions (open / closed eyes, smiling / not smiling), and facial details (glasses / no glasses). After extracting them on your computer, you need to prepare a .csv file containing the path of each image, along with their corresponding label.

    首先,您需要从面部数据库下载训练数据。 此数据包含40个不同主题中的每个主题的十个不同图像(400个图像)。 对于某些对象,图像是在不同的时间拍摄的,光线,面部表情(睁开/闭合的眼睛,微笑/不微笑)和面部细节(眼镜/不戴眼镜)是不同的。 将它们解压缩到计算机上之后,您需要准备一个.csv文件,其中包含每个图像的路径以及相应的标签。

    To make it easy, I have one TrainingData.txt in my Git repository. However, you need to edit the file and alter the paths of images as per your computer directory location.

    为简单起见,我在Git存储库中有一个TrainingData.txt。 但是,您需要根据计算机目录位置编辑文件并更改图像的路径。

    Note: the downloaded face database contains images in .pgm format. This format is not supported by Windows. To actually convert them to .jpg, I added PGMToJPGConverter to my repository. You can use to this to convert the images and have an actual look at the training data.

    注意 :下载的人脸数据库包含.pgm格式的图像。 Windows 不支持此格式。 为了将它们实际转换为.jpg,我将PGMToJPGConverter添加到了存储库中。 您可以使用它来转换图像并实际查看训练数据。

    After this, you can run the face recognition program. Below are the steps performed in the program:

    之后,您可以运行面部识别程序。 以下是程序中执行的步骤:

    1. OpenCV library is loaded as usual.

      OpenCV库照常加载

    2. The .csv file is read, and two ArrayList(s) are created. One for the matrix of images and other for their corresponding labels.

      读取.csv文件,并创建了两个ArrayList。 一个用于图像矩阵,另一个用于其相应的标签。

    3. Out of the 400 input images, the last entry in the list data structure is removed and saved for testing the trained model later.

      在这400个输入图像中,列表数据结构中的最后一个条目将被删除并保存以供以后测试训练后的模型。

    4. After that, the remaining 399 images are used for training the Eigenfaces algorithm.

      之后,将剩余的399张图像用于训练 Eigenfaces算法。

    5. Once training is complete, the model is asked to predict the label of the image we removed in step 3.

      训练完成后,将要求模型预测我们在步骤3中删除的图像的标签。

    Here, we can observe that the algorithm is able to predict the label of our test subject with a confidence value of 1807. The lower the value, the better the prediction. Similarly, you can perform this exercise with two other algorithms. The C++ code can be downloaded from here and here.

    在这里,我们可以观察到该算法能够预测置信度为1807的测试对象的标签。值越低,预测越好。 同样,您可以使用其他两种算法来执行此练习。 可以从此处此处下载C ++代码。

    Update (27th Dec 2018): In case you find building the openCV java bindings painful, then i have a good news for you. Recently, I have found an easier way to get all the openCV dependencies for java. For complete details, please refer my another article.

    更新(2018年12月27日) :如果您发现构建openCV Java绑定很麻烦,那么我对您来说是个好消息。 最近,我找到了一种获取Java所有openCV依赖项的简便方法。 有关完整的详细信息,请参阅我的另一篇文章

    Congratulations!! ? You made it to the end. And if you liked ?this article, hit that clap button below ?. It means a lot to me and it helps other people see the story.

    恭喜 !! ? 您做到了最后。 如果您喜欢这篇文章,请点击下面的拍手按钮。 这对我来说意义重大,而且可以帮助其他人了解这个故事。

    翻译自: https://www.freecodecamp.org/news/facial-recognition-using-opencv-in-java-92fa40c22f62/

    java opencv识别

    展开全文
  • java人脸识别

    千次阅读 2018-03-12 11:50:36
    运用百度云接口完成人脸识别(免费) 完成的项目例子 http://download.csdn.net/download/weixin_39549656/10216565 首先需要开通人脸识别每秒2次访问量免费 开通地址 ...amp;hmpl=%E4%BA%BA%E8%84%B8%E5%85%8...

    运用百度云接口完成人脸识别(免费)

    完成的项目例子
    http://download.csdn.net/download/weixin_39549656/10216565
    首先需要开通人脸识别每秒2次访问量免费
    开通地址
    http://ai.baidu.com/event/facefree?hmsr=developer&hmpl=%E4%BA%BA%E8%84%B8%E5%85%8D%E8%B4%B9
    这里写图片描述
    去控制台获得API Key和 Secret Key
    这里写图片描述
    文件目录
    这里写图片描述
    通过AuthService.java获得token

    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 获取token类
     */
    public class AuthService {
    
        /**
         * 获取权限token
         * @return 返回示例:
         * {
         * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
         * "expires_in": 2592000
         * }
         */
        public static String getAuth() {
    
            // 官网获取的 API Key 更新为你注册的
            String clientId = "百度云应用的AK";
    
            // 官网获取的 Secret Key 更新为你注册的
            String clientSecret = "百度云应用的SK";
    
            return getAuth(clientId, clientSecret);
        }
    
        /**
         * 获取API访问token
         * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
         * @param ak - 百度云官网获取的 API Key
         * @param sk - 百度云官网获取的 Securet Key
         * @return assess_token 示例:
         * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
         */
        public static String getAuth(String ak, String sk) {
            // 获取token地址
            String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
            String getAccessTokenUrl = authHost
                    // 1. grant_type为固定参数
                    + "grant_type=client_credentials"
                    // 2. 官网获取的 API Key
                    + "&client_id=" + ak
                    // 3. 官网获取的 Secret Key
                    + "&client_secret=" + sk;
            try {
                URL realUrl = new URL(getAccessTokenUrl);
                // 打开和URL之间的连接
                HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.err.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String result = "";
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                /**
                 * 返回结果示例
                 */
                System.err.println("result:" + result);
                JSONObject jsonObject = new JSONObject(result);
                String access_token = jsonObject.getString("access_token");
                return access_token;
            } catch (Exception e) {
                System.err.printf("获取token失败!");
                e.printStackTrace(System.err);
            }
            return null;
        }
        public static void main(String[] args) {
            System.out.println(getAuth());
    
    
        }
    
    }

    利用token 并下载响应的jar包 选择响应的图片路径代码
    FaceDetect .java

    import com.baidu.ai.aip.utils.Base64Util;
    import com.baidu.ai.aip.utils.FileUtil;
    import com.baidu.ai.aip.utils.HttpUtil;
    
    import java.net.URLEncoder;
    
    /**
    * 人脸探测
    */
    public class FaceDetect {
    
        /**
        * 重要提示代码中所需工具类
        * FileUtil,Base64Util,HttpUtil,GsonUtils请从
        * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
        * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
        * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
        * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
        * 下载
        */
        public static String detect() {
            // 请求url
            String url = "https://aip.baidubce.com/rest/2.0/face/v1/detect";
            try {
                // 本地文件路径
                String filePath = "[本地文件路径]";
                byte[] imgData = FileUtil.readFileByBytes(filePath);
                String imgStr = Base64Util.encode(imgData);
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");
    
                String param = "max_face_num=" + 5 + "&face_fields=" + "age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities" + "&image=" + imgParam;
    
                // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
                String accessToken = "[调用鉴权接口获取的token]";
    
                String result = HttpUtil.post(url, accessToken, param);
                System.out.println(result);
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static void main(String[] args) {
            FaceDetect.detect();
        }
    }

    测试成功如下

    {"result_num":1,"result":[{"location":{"left":77,"top":144,"width":149,"height":154},"face_probability":1,"rotation_angle":1,"yaw":-0.45118400454521,"pitch":5.3421592712402,"roll":1.474733710289,"landmark":[{"x":115,"y":169},{"x":185,"y":171},{"x":150,"y":212},{"x":149,"y":249}],"landmark72":[{"x":76,"y":170},{"x":78,"y":194},{"x":81,"y":219},{"x":87,"y":244},{"x":100,"y":270},{"x":123,"y":292},{"x":148,"y":300},{"x":173,"y":294},{"x":197,"y":273},{"x":212,"y":247},{"x":218,"y":222},{"x":223,"y":198},{"x":225,"y":173},{"x":99,"y":171},{"x":106,"y":166},{"x":114,"y":165},{"x":123,"y":167},{"x":130,"y":174},{"x":122,"y":175},{"x":114,"y":176},{"x":105,"y":174},{"x":115,"y":169},{"x":88,"y":155},{"x":98,"y":145},{"x":111,"y":144},{"x":123,"y":147},{"x":134,"y":155},{"x":122,"y":155},{"x":111,"y":153},{"x":99,"y":153},{"x":170,"y":175},{"x":178,"y":169},{"x":186,"y":167},{"x":193,"y":168},{"x":200,"y":174},{"x":194,"y":176},{"x":186,"y":178},{"x":178,"y":177},{"x":185,"y":171},{"x":166,"y":157},{"x":177,"y":149},{"x":188,"y":147},{"x":200,"y":148},{"x":210,"y":158},{"x":200,"y":157},{"x":189,"y":156},{"x":178,"y":157},{"x":140,"y":175},{"x":137,"y":190},{"x":134,"y":205},{"x":129,"y":220},{"x":139,"y":221},{"x":160,"y":221},{"x":170,"y":221},{"x":166,"y":205},{"x":163,"y":191},{"x":160,"y":176},{"x":150,"y":212},{"x":122,"y":248},{"x":135,"y":241},{"x":149,"y":241},{"x":163,"y":242},{"x":174,"y":249},{"x":163,"y":257},{"x":148,"y":261},{"x":134,"y":257},{"x":135,"y":247},{"x":149,"y":248},{"x":162,"y":248},{"x":162,"y":250},{"x":149,"y":250},{"x":136,"y":249}],"age":31.849361419678,"beauty":58.011905670166,"expression":0,"expression_probablity":0.99998700618744,"faceshape":[{"type":"square","probability":0.10893177986145},{"type":"triangle","probability":0.0039200717583299},{"type":"oval","probability":0.73189455270767},{"type":"heart","probability":0.052113145589828},{"type":"round","probability":0.10314042121172}],"gender":"male","gender_probability":0.99999928474426,"glasses":0,"glasses_probability":0.99999630451202,"race":"yellow","race_probability":0.99998033046722,"qualities":{"occlusion":{"left_eye":0,"right_eye":0,"nose":0,"mouth":0,"left_cheek":0,"right_cheek":0,"chin":0},"blur":0,"illumination":0,"completeness":0,"type":{"human":0.99938035011292,"cartoon":0.00061963585903868}}}],"log_id":4130331474}

    返回说明

    返回参数

    参数 类型 必选 说明
    log_id uint64 是 日志id
    result_num uint32 是 人脸数目
    result object[] 是 人脸属性对象的集合
    +age double 否 年龄。face_fields包含age时返回
    +beauty double 否 美丑打分,范围0-100,越大表示越美。face_fields包含beauty时返回
    +location object 是 人脸在图片中的位置
    ++left uint32 是 人脸区域离左边界的距离
    ++top uint32 是 人脸区域离上边界的距离
    ++width uint32 是 人脸区域的宽度
    ++height uint32 是 人脸区域的高度
    +face_probability double 是 人脸置信度,范围0-1
    +rotation_angle int32 是 人脸框相对于竖直方向的顺时针旋转角,[-180,180]
    +yaw double 是 三维旋转之左右旋转角[-90(左), 90(右)]
    +pitch double 是 三维旋转之俯仰角度[-90(上), 90(下)]
    +roll double 是 平面内旋转角[-180(逆时针), 180(顺时针)]
    +expression uint32 否 表情,0,不笑;1,微笑;2,大笑。face_fields包含expression时返回
    +expression_probability double 否 表情置信度,范围0~1。face_fields包含expression时返回
    +faceshape object[] 否 脸型置信度。face_fields包含faceshape时返回
    ++type string 是 脸型:square/triangle/oval/heart/round
    ++probability double 是 置信度:0~1
    +gender string 否 male、female。face_fields包含gender时返回
    +gender_probability double 否 性别置信度,范围[0~1],face_fields包含gender时返回
    +glasses uint32 否 是否带眼镜,0-无眼镜,1-普通眼镜,2-墨镜。face_fields包含glasses时返回
    +glasses_probability double 否 眼镜置信度,范围[0~1],face_fields包含glasses时返回
    +landmark object[] 否 4个关键点位置,左眼中心、右眼中心、鼻尖、嘴中心。face_fields包含landmark时返回
    ++x uint32 否 x坐标
    ++y uint32 否 y坐标
    +landmark72 object[] 否 72个特征点位置,face_fields包含landmark时返回
    ++x uint32 否 x坐标
    ++y uint32 否 y坐标
    +race string 否 yellow、white、black、arabs。face_fields包含race时返回
    +race_probability double 否 人种置信度,范围[0~1],face_fields包含race时返回
    +qualities object 否 人脸质量信息。face_fields包含qualities时返回
    ++occlusion object 是 人脸各部分遮挡的概率,范围[0~1],0表示完整,1表示不完整
    +++left_eye double 是 左眼遮挡比例
    +++right_eye double 是 右眼遮挡比例
    +++nose double 是 鼻子遮挡比例
    +++mouth double 是 嘴巴遮挡比例
    +++left_cheek double 是 左脸颊遮挡比例
    +++right_cheek double 是 右脸颊遮挡比例
    +++chin double 是 下巴遮挡比例
    ++blur double 是 人脸模糊程度,范围[0~1],0表示清晰,1表示模糊
    ++illumination - 是 取值范围在[0~255],表示脸部区域的光照程度
    ++completeness - 是 人脸完整度,0或1, 0为人脸溢出图像边界,1为人脸都在图像边界内
    ++type object 是 真实人脸/卡通人脸置信度
    +++human - 是 真实人脸置信度,[0~1],大于0.5可以判断为人脸
    +++cartoon - 是 卡通人脸置信度,[0~1]

    返回示例

    {
        "result_num": 1,
        "result": [
            {
                "location": {
                    "left": 117,
                    "top": 131,
                    "width": 172,
                    "height": 170
                },
                "face_probability": 1,
                "rotation_angle": 2,
                "yaw": -0.34859421849251,
                "pitch": 2.3033397197723,
                "roll": 1.9135693311691,
                "landmark": [
                    {
                        "x": 161.74819946289,
                        "y": 163.30244445801
                    },
                    ...
                ],
                "landmark72": [
                    {
                        "x": 115.86531066895,
                        "y": 170.0546875
                    },
                    ...
                ],
                "age": 29.298097610474,
                "beauty": 55.128883361816,
                "expression": 1,
                "expression_probablity": 0.5543018579483,
                "gender": "male",
                "gender_probability": 0.99979132413864,
                "glasses": 0,
                "glasses_probability": 0.99999964237213,
                "race": "yellow",
                "race_probability": 0.99999976158142,
                "qualities": {
                    "occlusion": {
                        "left_eye": 0,
                        "right_eye": 0,
                        "nose": 0,
                        "mouth": 0,
                        "left_cheek": 0.0064102564938366,
                        "right_cheek": 0.0057411273010075,
                        "chin": 0
                    },
                    "blur": 1.1886881756684e-10,
                    "illumination": 141,
                    "completeness": 1,
                    "type": {
                        "human": 0.99935841560364,
                        "cartoon": 0.00064159056637436
                    }
                }
            }
        ],
        "log_id": 2493878179101621
    }

    这里写图片描述

    展开全文
  • Java 实现人脸识别(基于百度人脸识别API)

    万次阅读 多人点赞 2018-06-28 09:38:43
    百度人脸识别技术文档 1.人脸识别的工具类和实体类 <dependency> <groupId>com.baidu.aip</groupId> <artifactId>java-sdk</artifactId> <version>4.4.0</...

    百度人脸识别技术文档

    1.人脸识别的工具类和实体类

    <dependency>
                <groupId>com.baidu.aip</groupId>
                <artifactId>java-sdk</artifactId>
                <version>4.4.0</version>
            </dependency>

     

    package com.baofoo.admin.web.request.controller;
    
    import com.baidu.aip.face.AipFace;
    import com.baidu.aip.face.FaceVerifyRequest;
    import com.baidu.aip.face.MatchRequest;
    import com.baidu.aip.util.Base64Util;
    import org.json.JSONObject;
    
    import java.io.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    
    /**
     * Created by BF100 on 2018/6/25.
     */
    public class FaceIdentifyUtil {
        //设置APPID/AK/SK
        public static final String APP_ID = "11429094";
        public static final String API_KEY = "V0wjNP0yctaIHqrvfGbfaKkC";
        public static 
    展开全文
  • JAVA实现人脸识别,活体检测之百度API

    万次阅读 热门讨论 2018-06-08 10:07:28
    <artifactId>java-sdk <version>4.3.2 然后获取所需的AppID、APIKey、SecretKey: 进入百度云,创建应用: 创建完成之后可看见如下: 获取AppID、APIKey、SecretKey后,导入一下代码: ...

    ----------------------------------------------------------------

    GitHub:https://github.com/reamZMX/led-

    -----------------------8/16更新---------------------------

    有人问源码:

    链接:https://pan.baidu.com/s/1WP37IBacu6VZwtNOUDbSYg 密码:vdzm

    在这

    --------------------------------------------------

    吃水不忘挖井人,挖井人博客在此:挖井人一挖井人二

    然后是官方的使用说明文档:地址

    以上,感谢。

    首先引入jar:

    maven:

        <dependency>
            <groupId>com.baidu.aip</groupId>
            <artifactId>java-sdk</artifactId>
            <version>4.3.2</version>
        </dependency>

    然后获取所需的AppID、APIKey、SecretKey:

    进入百度云,创建应用:

    创建完成之后可看见如下:

    获取AppID、APIKey、SecretKey后,导入一下代码:

    public class FaceSpot {
    	private static final String AppID = "";
    	private static final String APIKey = "";
    	private static final String SecretKey = "";
    
    	static AipFace client = null;
    	static {
    		client = new AipFace(AppID, APIKey, SecretKey);
    		// 可选:设置网络连接参数
    		client.setConnectionTimeoutInMillis(2000);
    		client.setSocketTimeoutInMillis(60000);
    	}
    
    	public static void main(String[] args) throws IOException {
    		 String filePath = "F:/3.jpg";
    		 byte[] imgData = FileToByte(new File(filePath));
    		 
    		 System.out.println(detectFace(imgData,"1"));
    //		String filePath1 = "F:/3.jpg";
    //		String filePath2 = "F:/7.jpg";
    //		byte[] imgData1 = FileUtil.readFileByBytes(filePath1);
    //		byte[] imgData2 = FileUtil.readFileByBytes(filePath2);
    //		System.out.println(faceverify(imgData1));
    	}
    
    	/**
    	 * 人脸检测
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public static String detectFace(File file, String max_face_num) {
    		try {
    			return detectFace(FileToByte(file), max_face_num);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 人脸检测
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public static String detectFace(byte[] arg0, String max_face_num) {
    		try {
    
    			HashMap<String, String> options = new HashMap<String, String>();
    			options.put("face_field", "age,beauty,expression,faceshape,gender,glasses,race,qualities");
    			options.put("max_face_num", "2");
    			options.put("face_type", "LIVE");
    
    			// 图片数据
    			String imgStr = Base64Util.encode(arg0);
    			String imageType = "BASE64";
    			JSONObject res = client.detect(imgStr, imageType, options);
    			System.out.println(res.toString(2));
    			return res.toString();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
        /**
         * 人脸比对
         * @param file1
         * @param file2
         * @return
         */
    	public static String matchFace(File file1, File file2) {
    		try {
    			return matchFace(FileToByte(file1), FileToByte(file2));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 人脸比对
    	 * 
    	 * @param arg0
    	 *            人脸1
    	 * @param arg1
    	 *            人脸2
    	 * @return
    	 */
    	public static String matchFace(byte[] arg0, byte[] arg1) {
    		String imgStr1 = Base64Util.encode(arg0);
    		String imgStr2 = Base64Util.encode(arg1);
    		MatchRequest req1 = new MatchRequest(imgStr1, "BASE64");
    		MatchRequest req2 = new MatchRequest(imgStr2, "BASE64");
    		ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
    		requests.add(req1);
    		requests.add(req2);
    		JSONObject res = client.match(requests);
    		return res.toString();
    	}
        
    	/**
    	 * 人脸搜索
    	 * @param file
    	 * @param groupIdList
    	 * @param userId
    	 * @return
    	 */
    	public static String searchFace(File file, String groupIdList, String userId) {
    		try {
    			return searchFace(FileToByte(file), groupIdList, userId);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 人脸搜索
    	 * 
    	 * @param arg0
    	 * @param groupIdList
    	 * @return
    	 */
    	public static String searchFace(byte[] arg0, String groupIdList, String userId) {
    		String imgStr = Base64Util.encode(arg0);
    		String imageType = "BASE64";
    		HashMap<String, String> options = new HashMap<String, String>();
    		options.put("quality_control", "NORMAL");
    		options.put("liveness_control", "LOW");
    		if (userId != null) {
    			options.put("user_id", userId);
    		}
    		options.put("max_user_num", "1");
    		JSONObject res = client.search(imgStr, imageType, groupIdList, options);
    		return res.toString(2);
    	}
        /**
         * 增加用户
         * @param file
         * @param userInfo
         * @param userId
         * @param groupId
         * @return
         */
    	public static String addUser(File file, String userInfo, String userId, String groupId) {
    		try {
    			return addUser(FileToByte(file), userInfo, userId, groupId);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 增加用户
    	 * 
    	 * @param arg0
    	 * @param userInfo
    	 * @param userId
    	 * @param groupId
    	 * @return
    	 */
    	public static String addUser(byte[] arg0, String userInfo, String userId, String groupId) {
    		String imgStr = Base64Util.encode(arg0);
    		String imageType = "BASE64";
    		HashMap<String, String> options = new HashMap<String, String>();
    		options.put("user_info", userInfo);
    		options.put("quality_control", "NORMAL");
    		options.put("liveness_control", "LOW");
    
    		JSONObject res = client.addUser(imgStr, imageType, groupId, userId, options);
    		return res.toString(2);
    	}
    
    	public static String updateUser(File file, String userInfo, String userId, String groupId) {
    		try {
    			return updateUser(FileToByte(file), userInfo, userId, groupId);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 更新用户
    	 * 
    	 * @param arg0
    	 * @param userInfo
    	 * @param userId
    	 * @param groupId
    	 * @return
    	 */
    	public static String updateUser(byte[] arg0, String userInfo, String userId, String groupId) {
    		String imgStr = Base64Util.encode(arg0);
    		String imageType = "BASE64";
    		HashMap<String, String> options = new HashMap<String, String>();
    		if (userInfo != null) {
    			options.put("user_info", userInfo);
    		}
    		options.put("quality_control", "NORMAL");
    		options.put("liveness_control", "LOW");
    
    		JSONObject res = client.updateUser(imgStr, imageType, groupId, userId, options);
    		return res.toString(2);
    	}
        /**
         * 删除用户人脸信息
         * @param userId
         * @param groupId
         * @param faceToken
         * @return
         */
    	public static String deleteUserFace(String userId, String groupId, String faceToken) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		// 人脸删除
    		JSONObject res = client.faceDelete(userId, groupId, faceToken, options);
    		return res.toString();
    	}
        /**
         * 查询用户信息
         * @param userId
         * @param groupId
         * @return
         */
    	public static String searchUserInfo(String userId, String groupId) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		// 用户信息查询
    		JSONObject res = client.getUser(userId, groupId, options);
    		return res.toString(2);
    	}
        /**
         * 获取用户人脸列表
         * @param userId
         * @param groupId
         * @return
         */
    	public static String getUserFaceList(String userId, String groupId) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		// 获取用户人脸列表
    		JSONObject res = client.faceGetlist(userId, groupId, options);
    		return res.toString(2);
    	}
        /**
         * 获取一组用户
         * @param groupId
         * @param returnNum
         * @return
         */
    	public static String getGroupUsers(String groupId, String returnNum) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		options.put("start", "0");
    		if (returnNum != null) {
    			options.put("length", returnNum);
    		}
    		// 获取用户列表
    		JSONObject res = client.getGroupUsers(groupId, options);
    		return res.toString(2);
    	}
        /**
         * 组用户复制
         * @param userId
         * @param srcGroupId
         * @param dstGroupId
         * @return
         */
    	public static String userCopy(String userId, String srcGroupId, String dstGroupId) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		options.put("src_group_id", srcGroupId);
    		options.put("dst_group_id", dstGroupId);
    		// 复制用户
    		JSONObject res = client.userCopy(userId, options);
    		return res.toString(2);
    	}
        /**
         * 删除用户
         * @param userId
         * @param groupId
         * @return
         */
    	public static String deleteUser(String userId, String groupId) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		// 人脸删除
    		JSONObject res = client.deleteUser(groupId, userId, options);
    		return res.toString();
    	}
        /**
         * 增加组信息
         * @param groupId
         * @return
         */
    	public static String addGroup(String groupId) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		// 创建用户组
    		JSONObject res = client.groupAdd(groupId, options);
    		return res.toString();
    	}
        /**
         * 删除
         * @param groupId
         * @return
         */
    	public static String deleteGroup(String groupId) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		// 创建用户组
    		JSONObject res = client.groupDelete(groupId, options);
    		return res.toString();
    	}
        /**
         * 获取组列表
         * @param length
         * @return
         */
    	public static String getGroupList(String length) {
    		HashMap<String, String> options = new HashMap<String, String>();
    		options.put("start", "0");
    		options.put("length", length);
    		// 组列表查询
    		JSONObject res = client.getGroupList(options);
    		return res.toString();
    	}
    	/**
    	 * 活体检测
    	 * @param arg0
    	 * @return
    	 */
    	public static String faceverify(byte[] arg0){
    		String imgStr = Base64Util.encode(arg0);
            String imageType = "BASE64";
            FaceVerifyRequest req = new FaceVerifyRequest(imgStr, imageType);
            ArrayList<FaceVerifyRequest> list = new ArrayList<FaceVerifyRequest>();
            list.add(req);
            JSONObject res = client.faceverify(list);
            return res.toString();
    	}
    
    	private static byte[] FileToByte(File file) throws IOException {
    		// 将数据转为流
    		InputStream content = new FileInputStream(file);
    		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
    		byte[] buff = new byte[100];
    		int rc = 0;
    		while ((rc = content.read(buff, 0, 100)) > 0) {
    			swapStream.write(buff, 0, rc);
    		}
    		// 获得二进制数组
    		return swapStream.toByteArray();
    	}
    
    }

    填入自己的AppID, APIKey, SecretKey;

    函数的参数可自行根据官方文档自己改一改,文件读取那边提供一下小帅的FileUtil并且处理好了异常:

    public class FileUtil {
    
        /**
         * 根据文件路径读取byte[] 数组
         */
        public static byte[] readFileByBytes(String filePath) throws IOException {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            } else {
                ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
                BufferedInputStream in = null;
    
                try {
                    in = new BufferedInputStream(new FileInputStream(file));
                    short bufSize = 1024;
                    byte[] buffer = new byte[bufSize];
                    int len1;
                    while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                        bos.write(buffer, 0, len1);
                    }
    
                    byte[] var7 = bos.toByteArray();
                    return var7;
                } finally {
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException var14) {
                        var14.printStackTrace();
                    }
    
                    bos.close();
                }
            }
        }
    }

    然后就是测试啦,测试的话,随便百度了一张美女的照片,然后看返回:

    {
      "timestamp": 1528422299,
      "result": {
        "face_list": [{
          "expression": {
            "probability": 0.9997190833,
            "type": "smile"
          },
          "face_probability": 1,
          "glasses": {
            "probability": 0.9999995232,
            "type": "none"
          },
          "location": {
            "height": 102,
            "rotation": -2,
            "width": 109,
            "left": 102.9398575,
            "top": 56.39219284
          },
          "age": 19,
          "gender": {
            "probability": 0.9999992847,
            "type": "female"
          },
          "face_shape": {
            "probability": 0.7517765164,
            "type": "heart"
          },
          "face_token": "706eaee3240ef0cc679ab209b1b71e0d",
          "beauty": 69.47167206,
          "race": {
            "probability": 0.9999864101,
            "type": "yellow"
          },
          "angle": {
            "yaw": -2.858289719,
            "roll": -2.302281618,
            "pitch": 9.867022514
          }
        }],
        "face_num": 1
      },
      "cached": 0,
      "error_code": 0,
      "log_id": 3671200838,
      "error_msg": "SUCCESS"
    }

    嗯,确实是美女,

    "beauty": 69.47167206

    好,然后通过浏览器开启摄像头来实时的试下,先上效果图:

    好,大家不用在意这些细节,比如颜值啥的。。

    我觉得颜值这项可能是假的,因为我做搞怪的表情时分数反而高一些??????????

    上代码吧。。

    首先是Controller:

    @Controller
    @RequestMapping(value = "/faceRecognition")
    public class faceRecognitionController {
    
    	 /**
    	 * 人脸检测测试页面
    	 * @return
    	 * @throws Exception  
    	 */
        @RequestMapping(value = "/test.do")
        public ModelAndView queryVoi() throws Exception {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("/artificialIntelligence/faceRecognition/test");
            return modelAndView;
        }
    	
        /**
       	 * 请求人脸检测
       	 * @return
       	 * @throws Exception  
       	 */
    	@RequestMapping(value = "/save.do")
    	@ResponseBody
    	public Map<String, Object> queryService(@RequestParam("the_file") MultipartFile file) {
    		Map<String, Object> modelMap = new HashMap<String, Object>();
    		try {
    			//将数据转为流
    			InputStream content = file.getInputStream();
    			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
    	        byte[] buff = new byte[100];  
    	        int rc = 0;  
    	        while ((rc = content.read(buff, 0, 100)) > 0) {  
    	            swapStream.write(buff, 0, rc);  
    	        }  
    	        //获得二进制数组
    	        byte[] in2b = swapStream.toByteArray(); 
    	        //调用人脸检测的方法
    	        String  str = FaceSpot.detectFace(in2b,""+1);
    	        JSONObject job = new JSONObject(FaceSpot.faceverify(in2b));
    			 System.out.println(job.toString());
    			 JSONObject testData = job.getJSONObject("result");
    			 //System.out.println(testData.get("face_liveness"));
    	        
    	        JSON json = JSON.parseObject(str);
                FaceV3DetectBean bean = JSON.toJavaObject(json, FaceV3DetectBean.class);
                JSONArray arr = new JSONArray();
                
    	     	 for(int i=0;i<bean.getResult().getFace_list().size();i++){
    			        JSONObject jsonObject = new JSONObject();
    			    	//获取年龄
    			        int ageOne = bean.getResult().getFace_list().get(i).getAge();
    			     	//处理年龄
    			        String age =String.valueOf(new BigDecimal(ageOne).setScale(0, BigDecimal.ROUND_HALF_UP));
    			        jsonObject.put("age", age);
    					
    					//获取美丑打分
    			        Double beautyOne = (Double) bean.getResult().getFace_list().get(i).getBeauty();
    					//处理美丑打分
    			     	String beauty =String.valueOf(new BigDecimal(beautyOne).setScale(0, BigDecimal.ROUND_HALF_UP));
    			     	jsonObject.put("beauty", beauty);
    					
    					//获取性别  male(男)、female(女)
    					String gender = (String) bean.getResult().getFace_list().get(i).getGender().getType();
    					jsonObject.put("gender", gender);
    					
    					//获取是否带眼睛 0-无眼镜,1-普通眼镜,2-墨镜
    					String glasses =  bean.getResult().getFace_list().get(i).getGlasses().getType();
    					jsonObject.put("glasses", String.valueOf(glasses));
    					
    					//获取是否微笑,0,不笑;1,微笑;2,大笑
    					String expression =  bean.getResult().getFace_list().get(i).getExpression().getType();
    					jsonObject.put("expression", String.valueOf(expression));
    					arr.put(jsonObject);
    			 }
    			modelMap.put("strjson", arr.toString());
    			modelMap.put("face_liveness", testData.get("face_liveness"));
    			modelMap.put("success", true);
    		} catch (Exception e) {
    			e.printStackTrace();
    			modelMap.put("success", false);
    			modelMap.put("data", e.getMessage());
    		}
    		return modelMap;
    	}
    	
    	
    }

    用的是fastjson,自行加jar包。

    然后是jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">	
    <title>人脸检测</title>
    <script src="js/jquery-2.1.1.js" type="text/javascript" charset="utf-8"></script>
    <script>
    
    	//判断浏览器是否支持HTML5 Canvas
    	window.onload = function () {
    		try {
    		//动态创建一个canvas元 ,并获取他2Dcontext。如果出现异常则表示不支持 document.createElement("canvas").getContext("2d");
    		 document.getElementById("support").innerHTML = "浏览器支持HTML5 CANVAS";
    		}
    		catch (e) {
    		 document.getElementByIdx("support").innerHTML = "浏览器不支持HTML5 CANVAS";
    		}
    	};
    	
    	//这段代 主要是获取摄像头的视频流并显示在Video 签中
    	window.addEventListener("DOMContentLoaded", function () {
    		var canvas = document.getElementById("canvas"),
    		context = canvas.getContext("2d"),
    		video = document.getElementById("video"),
    		videoObj = { "video": true },
    		errBack = function (error) {
    			console.log("Video capture error: ", error.code);
    		};
    		//拍照按钮
    // 		$("#snap").click(function () {
    // 			context.drawImage(video, 0, 0, 330, 250);
    // 			})
    		//拍照每秒一次
    		setInterval(function(){
    			context.drawImage(video, 0, 0, 330, 250)
    			CatchCode();
    		},1000);
    		//navigator.getUserMedia这个写法在Opera中好像是navigator.getUserMedianow
    		//更新兼容火狐浏览器
    		if (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
    			    navigator.getUserMedia=navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
    			    navigator.getUserMedia(videoObj, function (stream) {
    				video.srcObject  = stream;
    				video.play();
    				}, errBack);
    		}
    	
    	}, false);
    	
    	function dataURItoBlob(base64Data) {
    		var byteString;
    		if (base64Data.split(',')[0].indexOf('base64') >= 0)
    		byteString = atob(base64Data.split(',')[1]);
    		else
    		byteString = unescape(base64Data.split(',')[1]);
    		var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    		var ia = new Uint8Array(byteString.length);
    		for (var i = 0; i < byteString.length; i++) {
    		ia[i] = byteString.charCodeAt(i);
    		}
    		return new Blob([ia], {type:mimeString});
    	}
    	
    	//上传服务器
    	function CatchCode() {
    		var canvans = document.getElementById("canvas");
    		//获取浏览器页面的画布对象
    		//以下开始编 数据
    		var imageBase64 = canvans.toDataURL();
    		var blob = dataURItoBlob(imageBase64);  // 上一步中的函数
    		var fd = new FormData(document.forms[0]);
    		fd.append("the_file", blob, 'image.png');
    		//将图像转换为base64数据
    		$.ajax({
    	   		type:"POST",
    	   		url:"faceRecognition/save.do",
    	   		processData: false,     // 必须
    	      	contentType: false,     // 必须
    	      	data:fd,
    	    	datatype: "json",
    	   		success:function(data){
    		   		var mes = eval(data);
    		   		//alert(mes.success);
    		   		//var jsonObj =   $.parseJSON(mes.strjson); 
    		   		//alert(jsonObj[0].age);
    		   		if (mes.success) {
     		   			//alert(mes.strjson);
    		   			var jsonObj =  $.parseJSON(mes.strjson); 
    		   			//alert(jsonObj);
    		   			var age = jsonObj[0].age;
     		   			
    		   			var beauty = jsonObj[0].beauty;
    		   			var gendergender = jsonObj[0].gender;
    		   			var glasses = jsonObj[0].glasses;
    		   			var expression = jsonObj[0].expression
    		   			
    		   			$("#age").html(age);
    		   			$("#beauty").html(beauty);
    		   			$("#faceverify").html(mes.face_liveness);
    		   			
    		   			if(gendergender == 'male'){
    		   				$("#gendergender").html("男");
    		   			}else{
    		   				$("#gendergender").html("女");
    		   			}
    		   			
    		   			if(glasses == 'none'){
    		   				$("#glasses").html("未戴眼镜");
    		   			}else if(glasses == 'common'){
    		   				$("#glasses").html("戴了普通眼镜");
    		   			}else{
    		   				$("#glasses").html("戴了墨镜");
    		   			}
    					
    		   			if(expression == 'none'){
    		   				$("#expression").html("不笑");
    		   			}else if(expression == 'smile'){
    		   				$("#expression").html("微笑");
    		   			}else{
    		   				$("#expression").html("大笑");
    		   			}
    		   		}
    	   		},
    	   		error: function(){
    	    		//请求出错处理
    	    		alert("出情况了");
    	    		}         
    	  		});
    	}
    </script>
    <style> 
    .div-a{ float:left;width:60%;height:60%;border:1px solid #F00} 
    .div-b{ float:left;width:39%;height:60%;border:1px solid #000} 
    span{ font-size:25px }
    </style> 
    </head> 
    <body> 
    	<!-- 左边区域 -->
    	<div class="div-a" id="contentHolder">
    			<video id="video" width="100%" height="60%" autoplay></video>
    			<canvas style="" hidden="hidden"  id="canvas" width="520" height="250"></canvas>
    	</div> 
    	<!-- 右边区域 -->
    	<div class="div-b" >
    			<!-- 测试按钮 -->
    <!-- 		<input type="button" id="snap" style="width:100px;height:35px;" value="拍 照" /> -->
    <!-- 		<input type="button" onclick="CatchCode();" style="width:100px;height:35px;" value="上传服务器" /> -->
    		
    		<h1>人脸检测实时数据</h1>
    		<span>年龄:</span><span id="age"></span><br/>
    		<span>颜值:</span><span id="beauty" ></span><br/>
    		<span>性别:</span><span id="gendergender"></span><br/>
    		<span>是否戴眼镜:</span><span id="glasses"></span><br/>
    		<span>表情:</span><span id="expression"></span><br/>
    		<span>活体分数:</span><span id="faceverify"></span><br/>
    	</div> 
    		
    	</body>
    </html>

    这个貌似只支持火狐??我用其他浏览器摄像头并未开启,有哪位大神知道代码还请告诉在下,谢谢指教。

    这边有个活体指数,我测试了下,貌似还挺准,我首先百度了一张胡歌的照片放在摄像头上,emmmm.....颜值80,但是活体指数就很低,然后本人上,活体指数一直在0.95之上浮动,还是可靠的。

    好,告辞!

    展开全文
  • JAVA调用阿里云的人脸识别案例

    千次阅读 2019-04-11 16:52:52
    下面给出使用Java语言分别使用网络图片和本地图片调用人脸属性API的示例。 准备工作 1、拥有阿里云账号并开通了人脸识别服务,具体参考官方链接; 2、获取阿里云账户的AccessKey ID和Access Key Secret; 3...
  • 阿里云人脸识别Java调用示例参考

    千次阅读 2018-12-14 21:01:19
    概述 目前阿里云提供了关于...下面给出使用Java语言分别使用网络图片和本地图片调用人脸属性API的示例。 准备工作 1、拥有阿里云账号并开通了人脸识别服务,具体参考官方链接;2、获取阿里云账户的AccessKey ID和Ac...
  • 本文主要以简单讲解,百度人脸识别离线SDK(Java)版本工程运行入门级操作阐述。 项目地址 https://gitee.com/xshuai/BaiDuFaceOfflineSample SDK基础信息介绍 产品概述 人脸离线识别SDK,包含人脸采集、活体检测...
  • 可支持的人脸功能有:年龄、性别、头部姿态、微笑检测、胡须检测以及27个面部重要特征点位置等。FaceAPI 提供两个主要功能: 人脸检测和识别 目录: 申请subscription key示例效果开发示例AForge.Net 申请...
  • 本篇文章为简单的讲解百度离线人脸识别SDK-Java版本的工程运行;01注册百度AI开放平台登录http://ai.baidu.com进入百度AI开放平台,进行注册;02找到人脸识别模块,下载离线SDK1.找到相应模块2.下载SDK,当然如果没...
  • 以人脸识别为例,为了提高人脸检测的速度和精度,最终的分类器是通过几个强分类器级联得到,这就是所说的级联分类器。在一个级联分类系统中,对于每一个输入图片,顺序通过每个强分类器,前面的强分类器相对简单,其...
  • java调用face++实现人脸识别

    万次阅读 2018-02-11 13:37:49
    首先为什么我会选择旷视的face++呢,face++在人工智能尤其是在人脸识别是业内做的比较好的一家公司,又有自己的技术群,每天为人们解答各种疑难,为开发人员提供的好的帮助,我的这篇主要是应用于微信公众号开发当中...
  • Android Opencv smile(微笑识别开发

    千次阅读 2018-07-23 15:59:24
     //微笑处理&识别度  nestedCascade.detectMultiScale(smallImgROI, nestedObjects, 1.1, 0, 0  | CASCADE_SCALE_IMAGE, Size(30, 30));  // The number of detected neighbors depends on image size (and ...
  • 直接234. 第一步:鉴权服务技术方案 Java代码实现如下 import java.util.Date; import com.baidu.aip.util.Base64Util; /** * 获取Authorization * @author 小帅丶 * @类名称 Sign * @remark * @date
  • 首先要在 face++ 注册一个... 下载 java 接入工具,一个 jar 包:https://github.com/FacePlusPlus/facepp-java-sdk 请求返回的数据是 json 格式,需要导入 json 解析包: commons-beanutils-1.8.3.jar commons-...
  • 【AI】Java+Fileupload+JSTL+Face++实现人脸识别系统

    千次阅读 热门讨论 2017-09-14 15:46:25
     提供的技术包括了人脸检测、追踪、人脸关键点检测、 微笑分析、 性别、年龄、种族、1:1人脸验证、 1:N人脸识别、大规模人脸搜索。  小编亲测:上传狗或非人的照片,Face++是不会进行测试的。这个辩证的还是...
  • 人脸识别各家对比及虹软人脸识别系统Demo案例一、各个人脸识别公司、系统简介1.1 虹软1.2 Face++旷视1.3 云脉1.4 腾讯AI1.5 1MB轻量级人脸检测模型1.6 SeetaFace-科院计算机所开源项目二、基于虹软的Java人脸识别2.1...
  • JAVA虚拟机

    2020-02-07 11:56:00
    我相信每位Java人对这句话都不陌生,“一次编写,到处运行”,我们说这句话的底气就来自于 JVM( Java Virtual Machine)。 你可能花过很多精力学习 JVM 的知识,但在面对真实生产环境产生的问题,依旧会束手无策: ...
  • 带有Firebae ML Kit面部检测/识别功能的高低位纸牌游戏 这是通过Firebase ML Kit使用面部表情和头部移动来玩高低位纸牌游戏的小样本。 影片范例
  • 目录一、环境准备安装anconda3安装dlib库安装OpenCV库安装tensorflow安装keras环境检测二、人脸笑脸识别下载笑脸数据集划分测试集、训练集和验证集创建模型对图片进行归一化处理训练模型实现笑脸辨别三、人脸口罩...
  • 基于javaweb人脸识别

    2016-05-19 16:36:13
    人脸识别技术,可对人脸进行微笑程度,男女,年龄,种族 进行智能识别,还用到图片上传技术,接口调用。。。
  • 人脸脸部识别技术Terminator and similar movies depict a world that is controlled by AI and robots. For the mainstream this may seem outlandish, but notable figures like Elon Musk have expressed ...
  • 阿里Java面经大全(整合版)

    万次阅读 多人点赞 2018-08-03 16:10:12
    阿里巴巴,三面,java实习 昨天晚上11点打电话来,问我可以面试不,我说不可以,然后就约到了今天, 1.上来问我项目用的框架,然后问我springmvc里面有的参数的设定,问的是细节,然后问我如果传的多个值是一个...
  • 什么是Java虚拟机 从Java虚拟机所做的事情上去理解,可以分为两个阶段,编译时和运行时。编译时主要是一个由编译器将源码译为虚拟机指令集的一个过程;而运行时Java虚拟机主要涉及到类加载过程以及指令集的执行。 ...
  • Java语言特点: 简单性 面向对象(封装、继承、多态) 安全性 稳定性 高性能 多线程 分布性 JVM: JVM(Java Virtual Machine)是一个Java虚拟机,是运行 Java 字节码的虚拟机。Java字节码又是什么呢?那么我们的...
  • 今天老师要我们写一个简单的词法分析程序,实现简单的词法分析。... * author:微笑伯爵 * data:2021.10.26 */ public class Compile { /** * 程序要求识别如下: * * 识别保留字:begin end if then
  • C#winforms实现windows窗体人脸识别

    万次阅读 多人点赞 2017-11-30 22:16:21
    在之前我写过一篇博客,是关于javaweb实现人脸识别,包括数据库以及java源码,还有相关的jar包都已经上传了,有想要了解的可以去看看,地址是:java实现人脸识别源码 实现了之后又正好朋友开发C#,想要我顺便给写...
  • Java 编码规范

    2015-08-12 17:29:43
    以下规则并非指导或推荐的性质,而是必须遵守的规定。如果不遵守这些规定,Android通常不会接受投稿。...Java语言规范我们遵循标准的Java编码规范,并加入了新的规则:不要忽略异常有时,完全忽略

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,244
精华内容 497
关键字:

java微笑识别

java 订阅