Code Monkey home page Code Monkey logo

php-opencv-examples's Introduction

php-opencv-examples's People

Contributors

morozovsk avatar vicleos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-opencv-examples's Issues

Insightface Facial Recognition

Previously, you've mentioned that Insightface uses 512-D vectors of facial data here: #22 . However, when retrieving the vector data, it only shows 128 floats of data. Is this the expected result?

For facial recognition, the similarity percentage for Insightface can be rather low when comparing some Angelina pictures with other celebrities (I pulled pictures from here: https://www.kairos.com/demos). When running facial similarities among all the celebrities from the prior link using your code for Insightface, the similarities between 2 of the same person has a max of about 46% similarity and a min of 24%, which are both rather low. I was wondering if during your tests, you have noticed an optimal threshold for recognizing that a person is the same person and eliminating any false positives.

How to run your great works

Hi, Vladmir. Thanks for posting such a great thing.
But unfortunately, I am a new baby in OpenCV, so I can't find a way to implement your work.
It would be so appreciated if you kindly guide me how to install OpenCV and integrate with PHP and run your code!!!
Please help me. I really wish to run these works.
Will wait for your kind explanation.

Unable to install open cv

Being trying to install open cv so as to use it in my laravel app but its not being working ever since? any ideas

Support for php7.3

I'm triying to build the module and use it on php7.3, but it dump the core every time i try to run it, it's related to 7.3?

explanation

I tried the examples on Windows, but I befriended the problem of paths images and files, and corrected them by defining their full path, such as:
in the detect_face_by_cascade_classifier.php file
There is

line 8 :
$src = imread("images/faces.jpg");

put in place

$root = dirname(__FILE__).DIRECTORY_SEPARATOR;
$src = imread($root."images".DIRECTORY_SEPARATOR."faces.jpg");

this code run in all systeme
@morozovsk

ошибка клонирования репозитория из доков

при копипасте с wiki

root@6b2855f0eda5:/# git clone github.com/php-opencv/php-opencv-examples.git && cd php-opencv-examples
fatal: repository 'github.com/php-opencv/php-opencv-examples.git' does not exist

надо исправить на
git clone https://github.com/php-opencv/php-opencv-examples.git

open cv not found

I installed open cv to my home directory on my ubuntu but when i run this command ./configure --with-php-config=/opt/lampp/php-config --enable-debug i get no open cv found.

Line detection?

I'm looking for a software solution to detect lines in an image. OpenCV supports this, and seems this is an extension of that library.

Is this supported and I'm just not seeing it, or does it need a contribution to incorporate line detection from OpenCV in the library?

Need to crop image to detected face and save to file

Hello -

This is NOT an issue but a question. While I'm a experienced PHP programmer OpenCV is still a relatively new concept for me. I have successfully compiled the latest version of OpenCV and am currently using this extension in my environment. Going through the examples I've been able to derive a number of answers but I still keep running into a common roadblock.

Once I identify a face, calculate the new beginning and ending x,y coordinates I cannot seem to figure out how to crop that out of the Mat. I apologize of this seems like a obvious answer but it's just not coming to me.

Assuming my code starts like this ... what do I need to do to A) crop around the face, B) if not png convert to png and C) write to disk. I can do all these tasks in PHP but I feel keeping as much of this code native to opencv is important.

$faceClassifier = new CascadeClassifier();
$faceClassifier->load('../models/haarcascades/haarcascade_frontalface_default.xml');

$src = imread($scandir . "/" . $fileName);
$gray = cvtColor($src, COLOR_BGR2GRAY);

$faces = null;
$faceClassifier->detectMultiScale($gray, $faces);

//var_export($eyes);

if ($faces) {
    $scalar = new Scalar(0, 0, 255); //red

    foreach ($faces as $face) {
        $x = $face->x;
        $y = $face->y;
        $w = $face->width;
        $h = $face->height;

        $r = max($w, $h) / 2;
        $centerx = $x + $w / 2;
        $centery = $y + $h / 2;
        $nx = (int)($centerx - $r);
        $ny = (int)($centery - $r);
        $nr = (int)($r * 2);
    }

}

Any help would be greatly appreciated. In the best cases I would like to extract the cropped image from the $gray image but if it's a lot of trouble I can live with simply cropping it out of $src.
TIA

PHP OpenCV Library Issue

Sir.
I did integrating php-opencv to my project. while doing that, I got stuck at php library issue.
when I use your face recognition code sample, I came to face with undefined method error.
Here is error message.
{
"message": "Call to undefined method CV\Mat::data()",
"exception": "Error",
"file": "/var/www/vhosts/fofik.com/dbd.fofik.com/app/Services/CVDNNService.php",
"line": 89,
"trace": [
{
"file": "/var/www/vhosts/fofik.com/dbd.fofik.com/app/Http/Controllers/CelebController.php",
"line": 287,
"function": "recognize",
"class": "App\Services\CVDNNService",
"type": "->"
},
{
"file": "/var/www/vhosts/fofik.com/dbd.fofik.com/app/Http/Controllers/CelebController.php",
"line": 83,
"function": "vision",
"class": "App\Http\Controllers\CelebController",
"type": "->"
},
.........

and here is my code.

foreach ($cvData as $item) {
$label = $item->label;
$photo = $item->photo;
$src = imread(public_path($photo));
$faces = $this->image2faces($src);
foreach ($faces as $i => $face) {
$vec = $this->face2vec($face);
$faceVectors[$label.$i] = $vec->data();
}
}
and It's perfect same as you described on your example code.

I am really clueless about it.
when I print method list of $vec, there wasn't data method on it.

Array
(
[0] => __construct
[1] => type
[2] => depth
[3] => channels
[4] => empty
[5] => print
[6] => size
[7] => clone
[8] => ones
[9] => zeros
[10] => zerosBySize
[11] => isContinuous
[12] => isSubmatrix
[13] => row
[14] => col
[15] => at
[16] => atIdx
[17] => getImageROI
[18] => copyTo
[19] => convertTo
[20] => plus
[21] => divide
[22] => reshape
[23] => setTo
[24] => add
[25] => subtract
)
This is method list of CV\Mat class($vec) what I printed.
I hope you to take care of my trouble. solution for me please.
Thanks. N.J

why function predict not return value -1!

Hello, I am trying to use the php opencv library to recognize faces. However, the predict function always returns one of the labels I've trained, even though the face is untrained. And if only one tag is trained, no matter what the input image is, the result will always first label . How to fix it !!

How does the recognition work?

I get

php recognize_face_by_lbph.php
2, 88.481707039283
1, 113.10051890969

Isn't supposed to be the percentage?

When I replace the test page in recognize_face_by_lbph.php (images/angelina_and_me.png) with "images/2.jpg", where a match of 99% is expected, I get

php recognize_face_by_lbph.php // images2.jpg
1, 22.593326611433
php recognize_face_by_lbph.php // images1.jpg
1, 17.419620857298

Вопросы

Доброго дня!
Во-первых, огромное спасибо за столь прекрасную работу.
Во-вторых, уже почти год заглядываю сюда и у меня скопились вопросы, на которые у меня нет ответов. Если вы мне поможете с ответами, это было бы прекрасно!
Сначала о своей задаче: распознавание лиц на фотографиях, пришедших от терминала и определение, соответствует ли лицо аутентифицированному пользователю.
Вопросы:

  1. Нахождение фото, обучение и facemark
    Вот мы выбрали 10 фотографий одного человека, на которых мы будем проводить обучение.
    Для моих фотографий наиболее подходит haarcascade_frontalface_default.xml, которая хорошо находит лица.
    Посмотрели да, все лица вырезаны как нужно, можно обучить.
    Но вот стоп, а давайте посмотрим, как на этих лицах будут видны точки с помощью модели lbfmodel.yaml.
    Мы видим, что на фотографии неправильно определен рот. Он находится на месте усов. Поменяем фотографию. Возьмем те, где facemark показывает все нормально.
    И вот мы запускаем LBPHFaceRecognizer->train
    А вот ему же в принципе все равно, с помощью какой модели мы находили лицо, с помощью какой модели точки на фото показывали.
    Как понять, что переданные фотографии в LBPHFaceRecognizer->train действительно хороши для обучения?
  2. Обучение
    Мы получили точки с помощью facemark и они более-менее совпадают с лицом человека.
    Насколько я понимаю, в большинстве представленных на рынке решениях алгоритм, примерно следующий:
  • Получить числовое описание лица (у нас с помощью facemark получается 68 точек, кто-то 128 точек, кто-то 256);
  • Записать в базу числовое описание лица, присвоив ему метку;
  • При распознавании, получить числовое описание лица и сделать поиск по базе, для того чтобы найти максимальное приближение.
    Почему мы используем LBPHFaceRecognizer, которые не понятно, найдет ли те же точки? Почему мы не возьмем результат facemark для дальнейшего обучения? А если возьмем, то как, можно ли это сделать с помощью OpenCV?
  1. Владимир и Ангелина recognize_face_by_lbph.php
    В результате исполнения кода мы получаем, рамочки на лицах и угадывание кто есть, кто. Но самое главное, это Confidence – «уверенность». Она очень большая 113 и 88. Но, чем ближе «уверенность» к 0, тем лучше. Поэтому скорее это неуверенность. Просто повезло.
    В модель не заложено такое понятие как ‘unknown’. То есть если мы на фотографии разместим 3-е лицо, оно найдется и будет указано, что это либо Владимир, либо Ангелина с определенной степенью «уверенности». Для того, чтобы мы могли заложить понятие ‘unknown’, нам нужно понимать, а какая максимальная «уверенность» должна быть в модели. Как мы видим 113 и 88 это очень много. Я экспериментировал на разных количествах фото и лиц более 2000. Так вот нельзя подобрать какую-то «уверенность» для модели в целом. Нужно подбирать «уверенность» для конкретного искомого лица. Но и здесь не все хорошо.
    Упростим задачу. Сделаем систему «свой-чужой». Обучаем систему по 10 фотографиям одного человека по фамилии Пупкин. А потом начинаем детектировать. 200 фотографий Пупкина и 2000 фотографий других людей. Смотрим верность детектирования (рис.1).
    Модель свой-чужой
    На рисунке 1 гистограммы. Горизонтальная ось- «уверенность». Вертикальная ось – количество фотографий, которые попали в «уверенность».
    Коричневый цвет – уверенность при распознавании фотографий Пупкина.
    Синий цвет – фотографии других лиц.
    Пересечение гистограмм означает, что где-то в районе «уверенности» 35 система начинает во всех подряд узнавать Пупкина по обученной модели.
    То есть моделью можно пользоваться для узнавания Пупкина до того, как «уверенность» будет больше 35.
    Но и это нам не даст много толку, потому что, если мы ограничимся «уверенностью» 35, то большой процент фотографий где на самом деле есть Пупкин мы отметем. (Коричневые столбики после «уверенности» 35).
    Либо я что-то делаю не так, либо получается какая-то бестолковая модель. А?
  2. Еще про распознавание
    Если обучить модель по 10 фотографиям и отправить 1 из этих фотографий на распознавание, то система выдаст уверенность 0. Но! Если эту фотографию пересохранить в jpg. То уверенность увеличится до 10. Можно ли доверять такой системе?

Спасибо что прочитали. Выдохнул. Мне нужно было с кем-то поговорить. Я бы может и не написал, но вижу, что вы 9 дней назад обновили докер, значит вас эта тема очень захватывает.

Example works great. But in the model - ERR_EMPTY_RESPONSE

Good day Vladimir !

Tell me what's wrong with my code.
Example- Recognition_face_by_lbph.php is at the root of the site - it works great.
But if I want to do the same in the my model, I get the error ERR_EMPTY_RESPONSE.



<?php
use CV\Face\LBPHFaceRecognizer, CV\CascadeClassifier, CV\Scalar, CV\Point;
use function CV\{imread, cvtColor, equalizeHist};
use const CV\{COLOR_BGR2GRAY};

class opencv_model extends Model
{
    function __construct()
    {
    }
    function recognize_face()
    {

        $faceClassifier = new CascadeClassifier();
        $faceClassifier->load(URL . 'phpocv/models/lbpcascades/lbpcascade_frontalface.xml');

        $faceRecognizer = LBPHFaceRecognizer::create();

        $filenam = __DIR__.'/faces.jpg';
        $labels = ['unknown', 'vadim', 'alice'];

        $src = cv\imread($filenam);
        $gray = cvtColor($src, COLOR_BGR2GRAY);
      // until this - everyfing work fine
       $faceClassifier->detectMultiScale($gray, $faces); // if i uncomment this line - all broke down...

        var_dump($faces);
      
    }
}

Call to undefined function CV\imread()

Fatal error: Uncaught Error: Call to undefined function CV\imread() in /var/www/html/php-opencv-examples/detect_face_by_dnn_ssd.php:10 Stack trace: #0 {main} thrown in /var/www/html/php-opencv-examples/detect_face_by_dnn_ssd.php on line 10

Worked in terminal command: php detect_face_by_dnn_ssd.php
array ( 0 => 1, 1 => 1, 2 => 69, 3 => 7, )0.999955415725708 0.999824583530426

But got error when run on localhost.

Please help !

Uncaught Error: Call to undefined function CV\imread()

hi, i have this problem. i am installed opencv with this command:
apt update && apt install -y wget && \ wget https://raw.githubusercontent.com/php-opencv/php-opencv-packages/master/opencv_4.0.1_amd64.deb && dpkg -i opencv_4.0.1_amd64.deb && rm opencv_4.0.1_amd64.deb && \ wget https://raw.githubusercontent.com/php-opencv/php-opencv-packages/master/php-opencv_7.2-4.0.1_amd64.deb && dpkg -i php-opencv_7.2-4.0.1_amd64.deb && rm php-opencv_7.2-4.0.1_amd64.deb && \ echo "extension=opencv.so" > /etc/php/7.2/cli/conf.d/opencv.ini
Linux Mint 18.3 Sylvia
php 7.2.21

PHP Warning: PHP Startup: Unable to load dynamic library 'opencv.so' (tried: /usr/lib/php/20170718/opencv.so (/usr/lib/php/20170718/opencv.so: cannot open shared object file: No such file or directory), /usr/lib/php/20170718/opencv.so.so (/usr/lib/php/20170718/opencv.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 PHP Fatal error: Uncaught Error: Call to undefined function CV\imread() in /var/www/opencv.local/detect_face_by_dnn_ssd.php:7

Call to undefined function CV\imread()

I am getting this error please can you help?
Is there any file I should include?

[08-Dec-2020 20:33:05 Europe/Istanbul] PHP Fatal error: Uncaught Error: Call to undefined function CV\imread() in /home/yusufkar/opencv.yusufkarakaya.com.tr/detect_objects_by_dnn_mobilenet.php:11 Stack trace: #0 {main} thrown in /home/yusufkar/opencv.yusufkarakaya.com.tr/detect_objects_by_dnn_mobilenet.php on line 11

missing classes.txt

I want make just one question - how did you get file classes.txt ?
Im try to find any kind of something like this in internet and other pretrained models, but im fail in it. Can you explain how to extract this classes from pretrained model downloaded from internet or extract them from pbtxt or pb file ?

Circle on Skin Rush.

I am having one small project to just draw the line around the skin rush. Is that possible to use this library?

unable to get working "detect_objects_by_dnn_mobilenet.php"

Hello,

I'm testing your examples one by one but I mainly interested into detect objects but "detect_objects_by_dnn_mobilenet.php" doesn't returns same value as you show on wiki

I only get the following:

CV\Mat::__set_state(array(
   'type' => 5,
   'rows' => -1,
   'cols' => -1,
   'dims' => 4,
   'shape' => 
  array (
    0 => 1,
    1 => 1,
    2 => 100,
    3 => 7,
  ),
)

What I'm doing wrong?

Checking for the similarity of two photos

It will be possible to ask you to help me with one script, I can't finish it myself.
The essence of the script is this, I upload a photo, the script should check for similarity with the photos that I have in my folder.

<?php

use OpenCV\{
    Core,
    Face\FaceRecognizer,
    ImgProc
};

// Функция для загрузки изображения в формате OpenCV Mat из файла
function loadImage($imagePath)
{
    return ImgProc::imread($imagePath);
}

// Функция для обнаружения лиц на изображении с помощью алгоритма Haar Cascade
function detectFaces($image)
{
    // Загрузка каскадного классификатора для обнаружения лиц
    $cascadePath = 'models/haarcascade/haarcascade_frontalface_default.xml';
    $cascade = new Core\Classifier\CascadeClassifier();
    $cascade->load($cascadePath);

    // Преобразование изображения в оттенки серого для более эффективной обработки
    $grayImage = new Core\Mat();
    ImgProc::cvtColor($image, $grayImage, ImgProc::COLOR_BGR2GRAY);

    // Обнаружение лиц на изображении
    $faces = new Core\RectVector();
    $cascade->detectMultiScale($grayImage, $faces);

    return $faces;
}

// Загрузка изображения с двумя лицами для сравнения
$imagePath1 = 'images/Mariya.jpg';
$imagePath2 = 'images/Milana.jpg';

$image1 = loadImage($imagePath1);
$image2 = loadImage($imagePath2);

// Обнаружение лиц на первом изображении
$faces1 = detectFaces($image1);

// Обнаружение лиц на втором изображении
$faces2 = detectFaces($image2);

// Если обнаружено по одному лицу на каждом изображении
if ($faces1->size() == 1 && $faces2->size() == 1) {
    // Извлечение областей лиц из изображений
    $faceRect1 = $faces1->get(0);
    $faceRect2 = $faces2->get(0);

    // Извлечение только лиц из изображений
    $face1 = $image1->rowRange($faceRect1->y, $faceRect1->y + $faceRect1->height)->colRange($faceRect1->x, $faceRect1->x + $faceRect1->width);
    $face2 = $image2->rowRange($faceRect2->y, $faceRect2->y + $faceRect2->height)->colRange($faceRect2->x, $faceRect2->x + $faceRect2->width);

    // Преобразование изображений лиц в оттенки серого
    $grayFace1 = new Core\Mat();
    $grayFace2 = new Core\Mat();
    ImgProc::cvtColor($face1, $grayFace1, ImgProc::COLOR_BGR2GRAY);
    ImgProc::cvtColor($face2, $grayFace2, ImgProc::COLOR_BGR2GRAY);

    // Создание объекта распознавателя лиц
    $recognizer = FaceRecognizer::create();
    
    // Обучение распознавателя на первом лице
    $recognizer->train(new Core\MatVector([$grayFace1]), new Core\IntVector([1]));
    
    // Проверка схожести второго лица с первым
    $result = $recognizer->predict($grayFace2);
    
    // Вывод результата
    if ($result['label'] === 1 && $result['confidence'] <= 50) {
        echo "Лица схожи";
    } else {
        echo "Лица не схожи";
    }
} else {
    echo "Ошибка: Не удалось обнаружить лица на одном или обоих изображениях.";
}

PHP Fatal error: Uncaught Error: Class 'OpenCV\ImgProc' not found in
PHP7.4
OpenCV4.5.5+

Is there any way to add new trains data?

How are you?
Thank you for your sharing of great data.
I love it and I want to know the way to add new trains data dynamically.
Is there any way to implement it?
Thank you for your advice.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.