php-opencv / php-opencv-examples Goto Github PK
View Code? Open in Web Editor NEWTutorial for computer vision and machine learning in PHP 7/8 by opencv (installation + examples + documentation)
Tutorial for computer vision and machine learning in PHP 7/8 by opencv (installation + examples + documentation)
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
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
hello,
Could you please tell me how to install opencv in windows
This is the error I am getting while running the php file.
при копипасте с 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
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.
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
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?
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
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?
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?
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.
Digital Ocean server 1 Intel vCPU and 2GB of memory with Ubuntu 24.04, Apache2, PHP 8.3
Brand new server and messing around with this library. The server idles about 30-40% of memory with no users/activity.
If I process an object detection function for one image it jumps about 5-10%
If I process 5 images in a row in one function it hits 90% memory usage then the server is bogged down for quite some time (30-60 minutes) until the memory comes back down. CPU is normal, spikes up and then back down after the process ends, as you'd expect.
While I know I have wimpy sever specs for testing, I'm wondering if there is a memory leak, is there a function to tell opencv to release the memory usage after it processes an image?
At the time of writing this the memory is at 92% after processing 5 images. Reboot the server, let it idle for about 10 minutes and the memory is back down to 34%.
Any insight would be helpful. Thanks
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.
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.
Доброго дня!
Во-первых, огромное спасибо за столь прекрасную работу.
Во-вторых, уже почти год заглядываю сюда и у меня скопились вопросы, на которые у меня нет ответов. Если вы мне поможете с ответами, это было бы прекрасно!
Сначала о своей задаче: распознавание лиц на фотографиях, пришедших от терминала и определение, соответствует ли лицо аутентифицированному пользователю.
Вопросы:
Спасибо что прочитали. Выдохнул. Мне нужно было с кем-то поговорить. Я бы может и не написал, но вижу, что вы 9 дней назад обновили докер, значит вас эта тема очень захватывает.
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 !!
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
Please,
share de Dockerfile
https://hub.docker.com/r/morozovsk/php-opencv/
I am having one small project to just draw the line around the skin rush. Is that possible to use this library?
Being trying to install open cv so as to use it in my laravel app but its not being working ever since? any ideas
how do i run the docker image of this package docker pull hihozhou/opencv and cofigure it]
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+
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 ?
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);
}
}
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?
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
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 !
how can i use this package on my windows operating system
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.