php -v
If it's not installed, install PHP and OpenCV with the following commands:
sudo apt-get install php
sudo apt-get install php-opencv
<?php
// Load image
$image = cvimread("test.jpg");
// Convert to grayscale
$gray = cvcvtColor($image, CV_BGR2GRAY);
// Perform edge detection
$edges = cvCanny($gray, 50, 150);
// Display result
cvimshow("Edges", $edges);
cvwaitKey();
?>
In this code, the image is first converted to grayscale as edge detection typically works better in this format. The cvCanny() function then performs the edge extraction, with threshold values of 50 and 150. The processed result is displayed using cvimshow().
<?php
// Load image
$image = cvimread("test.jpg");
// Convert to grayscale
$gray = cvcvtColor($image, CV_BGR2GRAY);
// Perform edge detection
$edges = cvCanny($gray, 50, 150);
// Convert to color image
$color = cvcvtColor($edges, CV_GRAY2BGR);
// Find contours
$contours = cvindContours($edges, cvCV_RETR_EXTERNAL, cvCV_CHAIN_APPROX_SIMPLE);
// Draw contours
cvdrawContours($color, $contours, -1, [0, 255, 0], 2);
// Show result with contours
cvimshow("Edges with Contours", $color);
cvwaitKey();
?>
This part starts with the same preprocessing steps. Then it converts the edge map into a color image to allow colored contour drawing. The contours are extracted with cvindContours(), and drawn on the image using cvdrawContours() with a green color and 2-pixel thickness.
We hope this guide helps you better understand how to implement image edge detection and contouring using PHP and OpenCV, and inspires you to apply these techniques in your own projects. Continued practice and experimentation will further enhance your skills in building advanced image processing solutions.