Tutorial for computer vision and machine learning in PHP 7/8 by opencv (installation + examples + documentation)

Comments
  • PHP OpenCV Library Issue

    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

    opened by millicare 7
  • Вопросы

    Вопросы

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

    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 дней назад обновили докер, значит вас эта тема очень захватывает.

    opened by huppo 6
  • Installation via docker

    Installation via docker

    https://github.com/php-opencv/php-opencv-examples/wiki/installation-via-docker Use docker to install cannot install to local, only can test inside docker. Have another method to install opencv in windows?

    opened by ChanKimSiong 5
  • Uncaught Error: Call to undefined function CV\imread()

    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

    opened by dmytro-talko 3
  • Need to crop image to detected face and save to file

    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

    opened by jmashore 2
  • missing classes.txt

    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 ?

    opened by Forsakenrox 2
  • Example works great. But in the model - ERR_EMPTY_RESPONSE

    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);
          
        }
    }
    
    opened by Toutlemond 2
  • Insightface Facial Recognition

    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.

    opened by SteA1kSauce 1
  • How to run your great works

    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.

    opened by millicare 1
  • Call to undefined function CV\imread()

    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

    opened by ysfkarakaya 1
  • Call to undefined function CV\imread()

    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 !

    opened by quangduz 1
  • unable to get working

    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?

    opened by scramatte 1
  • Line detection?

    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?

    opened by kirkbushell 0
  •  why function predict not return value -1!

    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 !!

    opened by lethehung 0
Owner
null
A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM.

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM. s('string')->toTitleCase()->ensureRight('y') ==

Daniel St. Jules 2.5k Dec 28, 2022
Extensive, portable and performant handling of UTF-8 and grapheme clusters for PHP

Patchwork UTF-8 for PHP Patchwork UTF-8 gives PHP developpers extensive, portable and performant handling of UTF-8 and grapheme clusters. It provides

Nicolas Grekas 80 Sep 28, 2022
php-crossplane - Reliable and fast NGINX configuration file parser and builder

php-crossplane Reliable and fast NGINX configuration file parser and builder ℹ️ This is a PHP port of the Nginx Python crossplane package which can be

null 19 Jun 30, 2022
A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

A tiny PHP class-based program to analyze an input file and extract all of that words and detect how many times every word is repeated

Max Base 4 Feb 22, 2022
PHP library to detect and manipulate indentation of strings and files

indentation PHP library to detect and manipulate the indentation of files and strings Installation composer require --dev colinodell/indentation Usage

Colin O'Dell 34 Nov 28, 2022
A PHP class which allows the decoding and encoding of a wider variety of characters compared to the standard htmlentities and html_entity_decode functions.

The ability to encode and decode a certain set of characters called 'Html Entities' has existed since PHP4. Amongst the vast number of functions built into PHP, there are 4 nearly identical functions that are used to encode and decode html entities; despite their similarities, however, 2 of them do provide additional capabilities not available to the others.

Gavin G Gordon (Markowski) 2 Nov 12, 2022
The Universal Device Detection library will parse any User Agent and detect the browser, operating system, device used (desktop, tablet, mobile, tv, cars, console, etc.), brand and model.

DeviceDetector Code Status Description The Universal Device Detection library that parses User Agents and detects devices (desktop, tablet, mobile, tv

Matomo Analytics 2.4k Jan 5, 2023
Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way.

String Component The String component provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a un

Symfony 1.3k Dec 29, 2022
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

Jeremy Dorn 3.9k Jan 1, 2023
A fast PHP slug generator and transliteration library that converts non-ascii characters for use in URLs.

URLify for PHP A fast PHP slug generator and transliteration library, started as a PHP port of URLify.js from the Django project. Handles symbols from

Aband*nthecar 667 Dec 20, 2022
ColorJizz is a PHP library for manipulating and converting colors.

#Getting started: ColorJizz-PHP uses the PSR-0 standards for namespaces, so there should be no trouble using with frameworks like Symfony 2. ###Autolo

Mikeemoo 281 Nov 25, 2022
:clamp: HtmlMin: HTML Compressor and Minifier via PHP

??️ HtmlMin: HTML Compressor and Minifier for PHP Description HtmlMin is a fast and very easy to use PHP library that minifies given HTML5 source by r

Lars Moelleken 135 Dec 8, 2022
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

Jeremy Dorn 3.9k Jan 3, 2023
"結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件。 / "Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best PHP Chinese word segmentation module.

jieba-php "結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件,目前翻譯版本為 jieba-0.33 版本,未來再慢慢往上升級,效能也需要再改善,請有興趣的開發者一起加入開發!若想使用 Python 版本請前往 fxsjy/jieba 現在已經可以支援繁體中文!只要將字典切換為 bi

Fukuball Lin 1.2k Dec 31, 2022
highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages

highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages. It's a port of highlight.js by Ivan Sagalaev that makes full use of the language and style definitions of the original JavaScript project.

Geert Bergman 633 Dec 27, 2022
Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

cocur/slugify Converts a string into a slug. Developed by Florian Eckerstorfer in Vienna, Europe with the help of many great contributors. Features Re

Cocur 2.8k Dec 22, 2022
Library for free use Google Translator. With attempts connecting on failure and array support.

GoogleTranslateForFree Packagist: https://packagist.org/packages/dejurin/php-google-translate-for-free Library for free use Google Translator. With at

Yurii De 122 Dec 23, 2022
Convert strings between 13 naming conventions: Snake case, Camel case, Kebab case, Pascal case, Ada case, Train case, Cobol case, Macro case, Upper case, Lower case, Title case, Sentence case and Dot notation.

Case converter Use this library to convert string between: Name Method Output example ?? Camel case toCamel() myNameIsBond ??‍?? Pascal case toPascal(

Jawira Portugal 147 Dec 24, 2022
Highlight trailing spaces and delete them in a flash.

Trailing Spaces A Sublime Text plugin that allows you to… highlight trailing spaces and delete them in a flash! Synopsis Installation Alternative inst

Sublime Text Packages 884 Jan 4, 2023