javascript 的 Dlib

Dlib for javascript

我对 C++ 和 Dlib 还很陌生。我需要为浏览器开发面部标志检测器,想知道是否有人尝试使用例如 DLIB 进行编译。 ASM.js 在浏览器上工作。我没有在网上看到很多 DLib 面部标志性现场演示。

这是一个值得追求的想法吗?如果是,有人可以告诉我任何资源吗?

我在我的一个项目中也遇到了同样的问题。但是我用浏览器从 dlib 成功获取了人脸地标细节。

实际上我从用户那里获取图像并将其发送到服务器并将其保存在一个特定的文件夹中。然后通过 PHP 触发 dlib python 代码并获取地标点详细信息作为 json 格式。一旦我们得到一个点的详细信息,我们就可以用它做任何事情。

想法是

输入图像文件 --> 发送服务 --> 保存到文件夹 --> 触发 dlib python 脚本 --> 将点保存为 json 文件 --> 回显成功--> 获取 json

通过这种方式:

第 1 步: 首先在你的服务器上成功安装 Dlip(首先测试你的本地服务器)没有任何错误。并检查它的 运行 没有错误。

第 2 步: 然后我们想要 dlip 中的人脸界标。 dlip 有一个示例脚本 face_landmark_detection.py 我们可以使用它。

我的自定义 face_landmark_detection.py 脚本这是将点详细信息保存为特定路径中的 json 文件:

# python face_landmark_detection.py "predictor.dat" "folder/image.jpg" "folder/test.json" 

import dlib
import glob
import json
import os
from skimage import io
import sys



predictor_path = sys.argv[1]
#faces_folder_path = sys.argv[2]
image      = sys.argv[2]
json_path  = sys.argv[3]

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)






img = io.imread(image)
dets = detector(img, 1)
print(dets);
print("Number of faces detected: {}".format(len(dets)))
for k, d in enumerate(dets):

    print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
          k, d.left(), d.top(), d.right(), d.bottom()))

    # Get the landmarks/parts for the face in box d.
    shape = predictor(img, d)

    print("Part 0: {}, Part 1: {}, Part 3: {}  ...".format(shape.part(0),
          shape.part(1), shape.part(2), ))
    part1 = shape
    data = {}
    num = 0
    for n, p in enumerate(shape.parts()):
        n = format(n)
        p = format(p)
        p = p.split(",")
        x = p[0].split("(")
        x = x[1]
        y = p[1].split(" ")
        y = y[1].split(")")
        y = y[0]
        print(n, x, y)
        data[n] = {'x':x, 'y':y}
    out_file = open(json_path, "a")
    json.dump(data, out_file, sort_keys=True, indent=4)
    json_data = json.dumps(data, sort_keys=True);     
    print(json_data)        

我的服务器 php 脚本。此脚本从浏览器获取图像并将其保存在某个文件夹中,并使用预测器路径、图像路径、json 路径参数触发我的 face_landmark_detection.py

server.php 这样的文件

<?php

$target_dir = "/designing/face/uploads/";
$type = explode("/", $_FILES["file"]["type"]);
$type = $type[1];
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST)) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if ($check !== false) {

        $uploadOk = 1;
    } else {

        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    unlink($target_file);
    $uploadOk = 1;
}
// Check file size
/* if ($_FILES["file"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
  } */
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png") {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "error";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        //chmod($target_file, 0777);
        //echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";

        if ($imageFileType == "png") {
            $image = imagecreatefrompng($target_file);
            $bg = imagecreatetruecolor(imagesx($image), imagesy($image));
            imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
            imagealphablending($bg, TRUE);
            imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
            imagedestroy($image);
            $quality = 100; // 0 = worst / smaller file, 100 = better / bigger file 
            imagejpeg($bg, $target_file . ".jpg", $quality);
            imagedestroy($bg);
            unlink($target_file);
            $target_file = $target_file . ".jpg";
            //echo $target_file;
        }

        $json_file = fopen("/test/json/" . $_FILES["file"]["name"] . "_json.txt", "w");
        if ($json_file) {
            $command = 'python /face/face_landmark_detection.py "/face/predictor.dat" "' . $target_file . '" "/test/json/' . $_FILES["file"]["name"] . '_json.txt"';
            $output = shell_exec($command);
            if ($output) {
                //unlink($target_file);
                echo "ok";
            }
        }




        //echo $command;
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>  

我的客户端(浏览器)端脚本是这样的

$('#file').change(function() {
    var formData = new FormData();
    formData.append('file', $('input[type=file]')[0].files[0]);
    img = $('input[type=file]')[0].files[0];
    file_name = img.name;
    console.log(file_name);
    var reader = new FileReader();
    reader.onload = function(readerEvt) {
        data_url = readerEvt.target.result;
    };
    reader.readAsDataURL(img);
    $.ajax({
        url: base_url + "server.php",
        type: 'POST',
        data: formData,
        success: function(data) {
            console.log(data);
            if (data === "ok") {
                getJson(data_url, file_name);
            } else {
                alert("something worng");
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });
});
var pts;

function getJson(data_url, file_name) {
    console.log(file_name);
    var json_name = {
        'name': file_name
    };
    $.ajax({
        method: "POST",
        url: base_url + "get_json.php",
        crossDomain: true,
        data: json_name,
        dataType: 'JSON',
        success: function(data) {
            pts = data;
            console.log(pts);
            // alert(data_url);
        }
    });
}

一旦一切 运行 良好,我们就会得到一个 json 文件,其中包含 points 。我们可以用这些点在 canvas 上玩我们想玩的东西。首先你要了解整个过程。

我这里直接贴我的演示代码。查看代码并更改您想要的内容(如路径、参数...),然后 运行。

我通过这些方式成功获取了我的虚拟面部改造项目的点详细信息。我无法为您的演示提供我的项目 url,因为项目目前正在处理中。