Machine Vision: Install, configure and use Google Cloud Vision for PHP
- Tutorial
To date, Google has advanced significantly in the field of machine learning and artificial intelligence. The accumulated resources, both informational and financial, allow it to do so. All other companies or just enthusiasts have an excellent opportunity to use the collected knowledge, without having at the disposal of similar resources. Fortunately, the search engine gives such an opportunity for a fee. One of the tools that Google provides is machine vision, or Cloud Vision. The tool is very powerful, capable of analyzing a digital image in detail for images present on it, up to the mood of the characters in the photo. Below will be described in detail the process of installing, configuring and using Vision.
About payment
Google provides Cloud Vision for rent, charging a certain amount for each of the available options. For example, the option of defining images in an image costs $ 1.50 for 1000 photos. Approximately the same amount of search engine takes the remaining opportunities. You can view the full price list by the link . The good news is that each new Google account gives $ 300 to the account. This allows you to try free machine vision from a search engine with virtually no restrictions.
check in
Follow the link , click Try It Free and fill out the registration form. Separately, it is worth mentioning only that for work you will need to enter your billing information, even despite the $ 300 loan. Within this limit, nothing will be deducted from your card. These cards must be given real (as well as a contact phone number), but the name of the company can be thought up to anyone - no one checks. If you give incorrect contact or billing information, you will have to re-create your billing account, so let's get real data right away.
Installation
Installing the framework through Composer:
composer require google/cloud-vision
Here I note that when installing the library, Composer may not have enough memory if you have a weak server. I, for example, have 1GB of RAM, which was not enough. There are two ways out of the situation - either to expand server resources or install on a local machine (on most modern PCs there is more than 2GB, which is more than enough). After installation, the library files can be manually transferred to the server and work with the framework. You can install via WSL (Windows Subsystem for Linux), if you are on Windows, or via the Linux console using the command above.
The second note is the PHP version. Vision requires no lower than 7th. Upgrade if you are older.
Authentication
After installation, you need to somehow identify your installation by linking with a Google account. This is done through the key of the service account, which is stored inside the file on your server / local machine. To create a key, follow the link:
https://console.cloud.google.com/apis/credentials/serviceaccountkey?_ga=2.81515287.-1059122667.1452437442
In the single drop-down list, select "New service account", then enter the name in Latin (any that you understand). Do not select any role (not in this case). Click "Create" and feel free to skip the warning about the absence of a role. At the same time, the key file will be downloaded to your computer. Place the file in the same folder with the installed framework (project folder). This is optional, but easier. The framework requires that the file path is specifically indicated in the system. To do this, create an environment variable as follows:
export GOOGLE_APPLICATION_CREDENTIALS="/var/www/myproject/myproject_service.json"
The path to the file you will have is different - do not forget to change.
Using
Everything is set up, it's time to try Cloud Vision in action. Create a php file with the following content:
# включаем в наш код автозагрузчик установленного фреймворкаrequire__DIR__ . '/vendor/autoload.php';
# задаем использование конкретно библиотеки для анализа свойств изображенийuseGoogle\Cloud\Vision\V1\ImageAnnotatorClient;
# создаем экземпляр библиотеки
$imageAnnotator = new ImageAnnotatorClient();
# путь к файлу, который мы будем "показывать" машинному зрению
$fileName = 'test/data/cat.jpg';
# загружаем файл
$image = file_get_contents($fileName);
# "рассматриваем" загруженное изображение и выводим его атрибуты, или "лейблы"
$response = $imageAnnotator->labelDetection($image);
$labels = $response->getLabelAnnotations();
if ($labels) {
echo("Атрибуты изображения:" . PHP_EOL);
foreach ($labels as $label) {
echo($label->getDescription() . PHP_EOL);
}
} else {
echo('Атрибутов не найдено' . PHP_EOL);
}
The whole process is described in the comments to the code. First we include the framework in the code, create an instance of it, load the image for parsing into the code. It will need to be pre-put in the folder to which you designate. Further, the code will display in turn all the attributes that will determine the image. For example, it could be “cat”, “white fur”, “green grass” and more - all that Google Cloud Vision machine vision will see in the picture. And on this, in general, everything. You can save and use this information at your discretion. I will describe more sophisticated options for working with Vision in other articles.