Portrait segmentation is a core task in computer vision that separates people from the background in images. Baidu provides a portrait segmentation API, allowing developers to achieve this functionality easily. This article demonstrates how to connect PHP with Baidu Portrait Segmentation API through a practical example.
First, you need to register a Baidu developer account and create a new application to obtain API credentials. After logging into the Baidu AI Open Platform, go to the console, select 'Artificial Intelligence', then click 'Portrait Segmentation' to access the management page. Here, you can find the API Key and Secret Key for your application, which will be used in the following code.
Next, create a new PHP project using any IDE or text editor. Inside the project directory, create a PHP file, for example portrait_segmentation.php.
At the beginning of your PHP file, include the Baidu AI SDK dependency. Download the SDK package, extract it, copy the BDAAI folder to your project directory, and include the BDAAI/AipImageProcess.php file in your code. Example:
<?php require_once 'BDAAI/AipImageProcess.php'; ?>
Use the following code to create an AipImageProcess object as the client for Baidu Portrait Segmentation API. Pass the API Key, Secret Key, and App ID during creation:
// Initialize SDK $appId = 'your_app_id'; $apiKey = 'your_api_key'; $secretKey = 'your_secret_key'; $client = new BDAAIAipImageProcess($appId, $apiKey, $secretKey);
Use the $client object to call the portrait segmentation API. In this example, we use a local image test.jpg:
// Read the image
$image = file_get_contents('test.jpg');
// Call the portrait segmentation API
$result = $client->bodySeg($image);
// Save the segmentation result locally
file_put_contents('result.png', $result);
In the code above, file_get_contents reads the local image, $client->bodySeg($image) sends the request to the API, and file_put_contents saves the segmented result as result.png.
After completing the code, navigate to the project directory and execute the following command in the terminal:
php portrait_segmentation.php
The program will perform portrait segmentation and generate a new image file result.png as the segmentation result.
This article demonstrates a complete workflow of using PHP to connect with Baidu's Portrait Segmentation API. From preparation, project creation, API client setup, to running the program, developers can quickly learn how to perform portrait segmentation. Baidu AI's API makes image processing and computer vision development more convenient.