Я также сталкиваюсь с той же проблемой в одном из моих проектов. Но я успешно получаю информацию о наземных ориентирах лица из dlib с браузером.
На самом деле я получаю изображение от пользователя и отправляю на сервер, сохраняя его в одной конкретной папке. затем введите dlib python
код через PHP
и получите информацию о точном месте как формат json
. как только мы получим подробные данные, мы сможем что-то сделать с этим.
Идея заключается в том
входного файла изображения -> отправить служить -> сохранить в папку -> триггер dlib питон скрипт -> сохранить точку в виде файла 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
скрипта. этот скрипт получает изображение из браузера и сохраняет его в некоторой папке и запускает мой face_landmark_detection.py
с использованием пути прогнозирования, пути к изображению, аргументов json path.
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-файл с точками. С этими моментами мы можем играть то, что хотим на холсте. сначала вам нужно понять весь процесс.
Я непосредственно вставляю свой демо-код здесь. Посмотрите код и измените то, что вы хотите (например, путь, параметры ...), затем запустите.
Я успешно получаю данные о точках таким образом, чтобы мое виртуальное лицо делало над проектом. Я не могу дать вам свой проект для вашей демонстрации, потому что проект находится в процессе.
Вы пытаетесь создать систему, которая должна работать непосредственно внутри браузера через JS или с помощью серверного бэкэнд? Или, возможно, вы хотите создать какое-то расширение браузера? – Evgeniy
ASM.js выглядит немного мертвым - не стоит тратить слишком много усилий, чтобы обнаружить, что есть некоторые неполные биты –
Я пытаюсь создать решение JS на стороне клиента, которое может использовать Dlib.Как и clmtrackr.js или tracker.js – user1386173