A detecção facial detecta vários rostos dentro de uma imagem com os principais atributos faciais associados, como estado emocional ou wearing headwear
.
O reconhecimento facial específico individual não é compatível.

Solicitações de detecção facial
Configurar autenticação e projeto do GCP
Se você ainda não tiver criado um projeto do Google Cloud Platform (GCP) e credenciais de conta de serviço, faça isso agora. Expanda esta seção para instruções.
-
Faça login na sua conta do Google.
Se você ainda não tiver uma, inscreva-se.
-
Configure um projeto do Console do Cloud.
Clique para:
- Crie ou selecione um projeto.
- ativar Vision API para esse projeto;
- criar uma conta de serviço;
- fazer o download de uma chave privada como JSON.
É possível visualizar e gerenciar esses recursos a qualquer momento no Console do Cloud.
-
Defina a variável de ambiente
GOOGLE_APPLICATION_CREDENTIALS
como o caminho do arquivo JSON que contém a chave da conta de serviço. Essa variável só se aplica à sessão de shell atual. Dessa maneira, se você abrir uma nova sessão, defina a variável novamente.Exemplo: Linux ou macOS
Substitua [PATH] pelo caminho do arquivo JSON que contém a chave da conta de serviço.
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
Exemplo:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
Exemplo: Windows
Substitua [PATH] pelo caminho do arquivo JSON que contém a chave da conta de serviço.
Com o PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
Exemplo:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"
Com prompt de comando:
set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
- Instale e inicialize o SDK do Cloud..
Detectar rostos em uma imagem local
A API Vision pode realizar a detecção de recursos em um arquivo de imagem local enviando o conteúdo do arquivo de imagem como uma string codificada em base64 no corpo da sua solicitação.
REST e LINHA DE CMD
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
- base64-encoded-image: a representação
base64 (string ASCII) dos dados da imagem binária. Essa string precisa ser semelhante à seguinte:
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
Método HTTP e URL:
POST https://vision.googleapis.com/v1/images:annotate
Corpo JSON da solicitação:
{ "requests": [ { "image": { "content": "base64-encoded-image" }, "features": [ { "maxResults": 10, "type": "FACE_DETECTION" } ] } ] }
Para enviar a solicitação, escolha uma destas opções:
curl
Salve o corpo da solicitação em um arquivo chamado request.json
e execute o comando a seguir:
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/images:annotate
PowerShell
Salve o corpo da solicitação em um arquivo chamado request.json
e execute o comando a seguir:
$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK
e a resposta no formato JSON.
Uma resposta FACE_DETECTION
inclui caixas delimitadoras para todos os rostos detectados, pontos de referência detectados nos rostos (olhos, nariz, boca etc.) e classificações de confiança para propriedades de rosto e imagem (alegria, tristeza, raiva, surpresa etc.).
Resposta
{ "responses": [ { "faceAnnotations": [ { "boundingPoly": { "vertices": [ { "x": 1126, "y": 224 }, { "x": 2144, "y": 224 }, { "x": 2144, "y": 1407 }, { "x": 1126, "y": 1407 } ] }, "fdBoundingPoly": { "vertices": [ { "x": 1149, "y": 495 }, { "x": 1979, "y": 495 }, { "x": 1979, "y": 1325 }, { "x": 1149, "y": 1325 } ] }, "landmarks": [ { "type": "LEFT_EYE", "position": { "x": 1380.8185, "y": 743.84045, "z": 0.0021395613 } }, { "type": "RIGHT_EYE", "position": { "x": 1662.0685, "y": 755.5167, "z": -132.41025 } }, { "type": "LEFT_OF_LEFT_EYEBROW", "position": { "x": 1299.746, "y": 678.32825, "z": 70.48484 } }, { "type": "RIGHT_OF_LEFT_EYEBROW", "position": { "x": 1425.6302, "y": 681.8628, "z": -87.506454 } }, { "type": "LEFT_OF_RIGHT_EYEBROW", "position": { "x": 1558.2202, "y": 686.09814, "z": -151.19424 } }, { "type": "RIGHT_OF_RIGHT_EYEBROW", "position": { "x": 1774.0068, "y": 700.8744, "z": -147.01884 } }, { "type": "MIDPOINT_BETWEEN_EYES", "position": { "x": 1482.9568, "y": 744.6472, "z": -123.55287 } }, { "type": "NOSE_TIP", "position": { "x": 1445.8673, "y": 921.27625, "z": -202.87003 } }, { "type": "UPPER_LIP", "position": { "x": 1471.0441, "y": 1031.8804, "z": -137.91678 } }, { "type": "LOWER_LIP", "position": { "x": 1478.706, "y": 1140.3444, "z": -116.650894 } }, { "type": "MOUTH_LEFT", "position": { "x": 1397.0453, "y": 1074.5051, "z": -10.362965 } }, { "type": "MOUTH_RIGHT", "position": { "x": 1655.8596, "y": 1077.2307, "z": -110.53521 } }, { "type": "MOUTH_CENTER", "position": { "x": 1478.6444, "y": 1084.2994, "z": -116.58564 } }, { "type": "NOSE_BOTTOM_RIGHT", "position": { "x": 1575.067, "y": 946.60516, "z": -132.10355 } }, { "type": "NOSE_BOTTOM_LEFT", "position": { "x": 1396.0128, "y": 944.48035, "z": -52.012077 } }, { "type": "NOSE_BOTTOM_CENTER", "position": { "x": 1470.0845, "y": 970.4061, "z": -139.32004 } }, { "type": "LEFT_EYE_TOP_BOUNDARY", "position": { "x": 1369.846, "y": 731.5155, "z": -18.276585 } }, { "type": "LEFT_EYE_RIGHT_CORNER", "position": { "x": 1429.0255, "y": 758.3745, "z": -23.542086 } }, { "type": "LEFT_EYE_BOTTOM_BOUNDARY", "position": { "x": 1371.9097, "y": 775.1022, "z": -0.9920981 } }, { "type": "LEFT_EYE_LEFT_CORNER", "position": { "x": 1334.5302, "y": 752.3428, "z": 52.589348 } }, { "type": "LEFT_EYE_PUPIL", "position": { "x": 1369.7902, "y": 752.99426, "z": -4.5812535 } }, { "type": "RIGHT_EYE_TOP_BOUNDARY", "position": { "x": 1646.1317, "y": 740.8714, "z": -149.13914 } }, { "type": "RIGHT_EYE_RIGHT_CORNER", "position": { "x": 1722.3821, "y": 765.43964, "z": -130.75653 } }, { "type": "RIGHT_EYE_BOTTOM_BOUNDARY", "position": { "x": 1659.9559, "y": 784.7147, "z": -132.99072 } }, { "type": "RIGHT_EYE_LEFT_CORNER", "position": { "x": 1593.8276, "y": 765.21747, "z": -102.17816 } }, { "type": "RIGHT_EYE_PUPIL", "position": { "x": 1652.9113, "y": 762.5403, "z": -139.53206 } }, { "type": "LEFT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 1354.2014, "y": 642.7664, "z": -27.636467 } }, { "type": "RIGHT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 1653.919, "y": 652.8384, "z": -169.58447 } }, { "type": "LEFT_EAR_TRAGION", "position": { "x": 1359.5302, "y": 899.9487, "z": 427.43317 } }, { "type": "RIGHT_EAR_TRAGION", "position": { "x": 1989.5599, "y": 921.3098, "z": 129.99654 } }, { "type": "FOREHEAD_GLABELLA", "position": { "x": 1487.4016, "y": 680.26874, "z": -130.2485 } }, { "type": "CHIN_GNATHION", "position": { "x": 1492.2446, "y": 1278.0455, "z": -77.825676 } }, { "type": "CHIN_LEFT_GONION", "position": { "x": 1330.9834, "y": 1094.7004, "z": 301.41083 } }, { "type": "CHIN_RIGHT_GONION", "position": { "x": 1897.9647, "y": 1114.2906, "z": 32.6488 } } ], "rollAngle": 1.7871192, "panAngle": -25.329906, "tiltAngle": -0.32616663, "detectionConfidence": 0.8218701, "landmarkingConfidence": 0.5853151, "joyLikelihood": "VERY_LIKELY", "sorrowLikelihood": "VERY_UNLIKELY", "angerLikelihood": "VERY_UNLIKELY", "surpriseLikelihood": "VERY_UNLIKELY", "underExposedLikelihood": "VERY_UNLIKELY", "blurredLikelihood": "VERY_UNLIKELY", "headwearLikelihood": "VERY_UNLIKELY" }, { "boundingPoly": { "vertices": [ { "x": 168, "y": 1305 }, { "x": 793, "y": 1305 }, { "x": 793, "y": 1844 }, { "x": 168, "y": 1844 } ] }, "fdBoundingPoly": { "vertices": [ { "x": 234, "y": 1454 }, { "x": 701, "y": 1454 }, { "x": 701, "y": 1844 }, { "x": 234, "y": 1844 } ] }, "landmarks": [ { "type": "LEFT_EYE", "position": { "x": 355.4812, "y": 1633.7351, "z": -0.00096174295 } }, { "type": "RIGHT_EYE", "position": { "x": 563.05676, "y": 1598.2274, "z": -15.432735 } }, { "type": "LEFT_OF_LEFT_EYEBROW", "position": { "x": 295.2572, "y": 1596.3945, "z": 27.602434 } }, { "type": "RIGHT_OF_LEFT_EYEBROW", "position": { "x": 399.66183, "y": 1574.5125, "z": -34.742764 } }, { "type": "LEFT_OF_RIGHT_EYEBROW", "position": { "x": 489.41595, "y": 1561.8435, "z": -41.881912 } }, { "type": "RIGHT_OF_RIGHT_EYEBROW", "position": { "x": 604.66504, "y": 1553.2301, "z": 2.8025007 } }, { "type": "MIDPOINT_BETWEEN_EYES", "position": { "x": 445.71527, "y": 1603.4773, "z": -46.01044 } }, { "type": "NOSE_TIP", "position": { "x": 458.00195, "y": 1706.4338, "z": -113.76316 } }, { "type": "UPPER_LIP", "position": { "x": 469.05304, "y": 1780.2344, "z": -78.998 } }, { "type": "LOWER_LIP", "position": { "x": 480.0647, "y": 1842.2673, "z": -73.402145 } }, { "type": "MOUTH_LEFT", "position": { "x": 398.64343, "y": 1820.1232, "z": -23.800583 } }, { "type": "MOUTH_RIGHT", "position": { "x": 558.57007, "y": 1797.7144, "z": -36.007656 } }, { "type": "MOUTH_CENTER", "position": { "x": 475.6739, "y": 1809.3279, "z": -68.785324 } }, { "type": "NOSE_BOTTOM_RIGHT", "position": { "x": 519.20447, "y": 1717.9144, "z": -47.30806 } }, { "type": "NOSE_BOTTOM_LEFT", "position": { "x": 410.96085, "y": 1739.2937, "z": -38.647636 } }, { "type": "NOSE_BOTTOM_CENTER", "position": { "x": 464.29404, "y": 1739.8107, "z": -74.77752 } }, { "type": "LEFT_EYE_TOP_BOUNDARY", "position": { "x": 358.2863, "y": 1615.2714, "z": -11.324151 } }, { "type": "LEFT_EYE_RIGHT_CORNER", "position": { "x": 395.53445, "y": 1626.9333, "z": -2.3256185 } }, { "type": "LEFT_EYE_BOTTOM_BOUNDARY", "position": { "x": 355.713, "y": 1645.1017, "z": -3.0947497 } }, { "type": "LEFT_EYE_LEFT_CORNER", "position": { "x": 325.97894, "y": 1637.1458, "z": 19.892412 } }, { "type": "LEFT_EYE_PUPIL", "position": { "x": 357.76205, "y": 1629.1317, "z": -4.846803 } }, { "type": "RIGHT_EYE_TOP_BOUNDARY", "position": { "x": 543.97064, "y": 1589.2532, "z": -26.101141 } }, { "type": "RIGHT_EYE_RIGHT_CORNER", "position": { "x": 586.45276, "y": 1600.4672, "z": -0.70706856 } }, { "type": "RIGHT_EYE_BOTTOM_BOUNDARY", "position": { "x": 560.2284, "y": 1612.6013, "z": -17.874813 } }, { "type": "RIGHT_EYE_LEFT_CORNER", "position": { "x": 515.07983, "y": 1609.0634, "z": -11.378595 } }, { "type": "RIGHT_EYE_PUPIL", "position": { "x": 548.1346, "y": 1602.3792, "z": -20.216436 } }, { "type": "LEFT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 342.54276, "y": 1561.4143, "z": -13.184053 } }, { "type": "RIGHT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 543.37683, "y": 1533.3728, "z": -29.198135 } }, { "type": "LEFT_EAR_TRAGION", "position": { "x": 276.39093, "y": 1762.4656, "z": 228.13643 } }, { "type": "RIGHT_EAR_TRAGION", "position": { "x": 698.24506, "y": 1702.8165, "z": 193.92969 } }, { "type": "FOREHEAD_GLABELLA", "position": { "x": 443.33896, "y": 1564.7924, "z": -45.18563 } }, { "type": "CHIN_GNATHION", "position": { "x": 493.31305, "y": 1928.5846, "z": -57.822914 } }, { "type": "CHIN_LEFT_GONION", "position": { "x": 305.68286, "y": 1868.2653, "z": 135.39107 } }, { "type": "CHIN_RIGHT_GONION", "position": { "x": 685.4797, "y": 1815.4688, "z": 104.89257 } } ], "rollAngle": -7.3906693, "panAngle": -4.5714307, "tiltAngle": 7.181163, "detectionConfidence": 0.7173322, "landmarkingConfidence": 0.5315869, "joyLikelihood": "VERY_UNLIKELY", "sorrowLikelihood": "VERY_UNLIKELY", "angerLikelihood": "VERY_UNLIKELY", "surpriseLikelihood": "VERY_UNLIKELY", "underExposedLikelihood": "VERY_UNLIKELY", "blurredLikelihood": "POSSIBLE", "headwearLikelihood": "VERY_UNLIKELY" } ] } ] }
C#
Antes de testar esta amostra, siga as instruções de configuração do C# no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para C#.
// Load an image from a local file.
var image = Image.FromFile(filePath);
var client = ImageAnnotatorClient.Create();
var response = client.DetectFaces(image);
int count = 1;
foreach (var faceAnnotation in response)
{
Console.WriteLine("Face {0}:", count++);
Console.WriteLine(" Joy: {0}", faceAnnotation.JoyLikelihood);
Console.WriteLine(" Anger: {0}", faceAnnotation.AngerLikelihood);
Console.WriteLine(" Sorrow: {0}", faceAnnotation.SorrowLikelihood);
Console.WriteLine(" Surprise: {0}", faceAnnotation.SurpriseLikelihood);
}
Go
Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Go.
// detectFaces gets faces from the Vision API for an image at the given file path.
func detectFaces(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
defer client.Close()
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
image, err := vision.NewImageFromReader(f)
if err != nil {
return err
}
annotations, err := client.DetectFaces(ctx, image, nil, 10)
if err != nil {
return err
}
if len(annotations) == 0 {
fmt.Fprintln(w, "No faces found.")
} else {
fmt.Fprintln(w, "Faces:")
for i, annotation := range annotations {
fmt.Fprintln(w, " Face", i)
fmt.Fprintln(w, " Anger:", annotation.AngerLikelihood)
fmt.Fprintln(w, " Joy:", annotation.JoyLikelihood)
fmt.Fprintln(w, " Surprise:", annotation.SurpriseLikelihood)
}
}
return nil
}
Java
Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da API Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Java.
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.FaceAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DetectFaces {
public static void detectFaces() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "path/to/your/image/file.jpg";
detectFaces(filePath);
}
// Detects faces in the specified local image.
public static void detectFaces(String filePath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
for (FaceAnnotation annotation : res.getFaceAnnotationsList()) {
System.out.format(
"anger: %s%njoy: %s%nsurprise: %s%nposition: %s",
annotation.getAngerLikelihood(),
annotation.getJoyLikelihood(),
annotation.getSurpriseLikelihood(),
annotation.getBoundingPoly());
}
}
}
}
}
Node.js
Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Node.js.
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const fileName = 'Local image file, e.g. /path/to/image.png';
const [result] = await client.faceDetection(fileName);
const faces = result.faceAnnotations;
console.log('Faces:');
faces.forEach((face, i) => {
console.log(` Face #${i + 1}:`);
console.log(` Joy: ${face.joyLikelihood}`);
console.log(` Anger: ${face.angerLikelihood}`);
console.log(` Sorrow: ${face.sorrowLikelihood}`);
console.log(` Surprise: ${face.surpriseLikelihood}`);
});
PHP
Antes de testar esta amostra, siga as instruções de configuração do PHP no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para PHP.
namespace Google\Cloud\Samples\Vision;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
function detect_face($path, $outFile = null)
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
// $path = 'path/to/your/image.jpg'
$image = file_get_contents($path);
$response = $imageAnnotator->faceDetection($image);
$faces = $response->getFaceAnnotations();
# names of likelihood from google.cloud.vision.enums
$likelihoodName = ['UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY',
'POSSIBLE', 'LIKELY', 'VERY_LIKELY'];
printf("%d faces found:" . PHP_EOL, count($faces));
foreach ($faces as $face) {
$anger = $face->getAngerLikelihood();
printf("Anger: %s" . PHP_EOL, $likelihoodName[$anger]);
$joy = $face->getJoyLikelihood();
printf("Joy: %s" . PHP_EOL, $likelihoodName[$joy]);
$surprise = $face->getSurpriseLikelihood();
printf("Surprise: %s" . PHP_EOL, $likelihoodName[$surprise]);
# get bounds
$vertices = $face->getBoundingPoly()->getVertices();
$bounds = [];
foreach ($vertices as $vertex) {
$bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
}
print('Bounds: ' . join(', ', $bounds) . PHP_EOL);
print(PHP_EOL);
}
}
Python
Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Python.
def detect_faces(path):
"""Detects faces in an image."""
from google.cloud import vision
import io
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.face_detection(image=image)
faces = response.face_annotations
# Names of likelihood from google.cloud.vision.enums
likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
'LIKELY', 'VERY_LIKELY')
print('Faces:')
for face in faces:
print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in face.bounding_poly.vertices])
print('face bounds: {}'.format(','.join(vertices)))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
Ruby
Antes de testar esta amostra, siga as instruções de configuração do Ruby no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Ruby.
# image_path = "Path to local image file, eg. './image.png'"
require "google/cloud/vision"
image_annotator = Google::Cloud::Vision.image_annotator
response = image_annotator.face_detection image: image_path
response.responses.each do |res|
res.face_annotations.each do |face|
puts "Joy: #{face.joy_likelihood}"
puts "Anger: #{face.anger_likelihood}"
puts "Sorrow: #{face.sorrow_likelihood}"
puts "Surprise: #{face.surprise_likelihood}"
end
end
Detectar rostos em uma imagem remota
Para comodidade, a API do Vision pode realizar a detecção de recursos diretamente em um arquivo de imagem localizado no Google Cloud Storage ou na Web, sem a necessidade de enviar o conteúdo do arquivo de imagem no corpo da solicitação.
REST e LINHA DE CMD
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
- cloud-storage-image-uri: o caminho para um arquivo de imagem
válido em um bucket do Cloud Storage. Você precisa ter, pelo menos, privilégios de leitura para o arquivo.
Exemplo:
gs://cloud-samples-data/vision/face/faces.jpeg
Método HTTP e URL:
POST https://vision.googleapis.com/v1/images:annotate
Corpo JSON da solicitação:
{ "requests": [ { "image": { "source": { "imageUri": "cloud-storage-image-uri" } }, "features": [ { "maxResults": 10, "type": "FACE_DETECTION" } ] } ] }
Para enviar a solicitação, escolha uma destas opções:
curl
Salve o corpo da solicitação em um arquivo chamado request.json
e execute o comando a seguir:
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/images:annotate
PowerShell
Salve o corpo da solicitação em um arquivo chamado request.json
e execute o comando a seguir:
$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
Quando a solicitação é bem-sucedida, o servidor retorna um código de status HTTP 200 OK
e a resposta no formato JSON.
Uma resposta FACE_DETECTION
inclui caixas delimitadoras para todos os rostos detectados, pontos de referência detectados nos rostos (olhos, nariz, boca etc.) e classificações de confiança para propriedades de rosto e imagem (alegria, tristeza, raiva, surpresa etc.).
Resposta
{ "responses": [ { "faceAnnotations": [ { "boundingPoly": { "vertices": [ { "x": 1126, "y": 224 }, { "x": 2144, "y": 224 }, { "x": 2144, "y": 1407 }, { "x": 1126, "y": 1407 } ] }, "fdBoundingPoly": { "vertices": [ { "x": 1149, "y": 495 }, { "x": 1979, "y": 495 }, { "x": 1979, "y": 1325 }, { "x": 1149, "y": 1325 } ] }, "landmarks": [ { "type": "LEFT_EYE", "position": { "x": 1380.8185, "y": 743.84045, "z": 0.0021395613 } }, { "type": "RIGHT_EYE", "position": { "x": 1662.0685, "y": 755.5167, "z": -132.41025 } }, { "type": "LEFT_OF_LEFT_EYEBROW", "position": { "x": 1299.746, "y": 678.32825, "z": 70.48484 } }, { "type": "RIGHT_OF_LEFT_EYEBROW", "position": { "x": 1425.6302, "y": 681.8628, "z": -87.506454 } }, { "type": "LEFT_OF_RIGHT_EYEBROW", "position": { "x": 1558.2202, "y": 686.09814, "z": -151.19424 } }, { "type": "RIGHT_OF_RIGHT_EYEBROW", "position": { "x": 1774.0068, "y": 700.8744, "z": -147.01884 } }, { "type": "MIDPOINT_BETWEEN_EYES", "position": { "x": 1482.9568, "y": 744.6472, "z": -123.55287 } }, { "type": "NOSE_TIP", "position": { "x": 1445.8673, "y": 921.27625, "z": -202.87003 } }, { "type": "UPPER_LIP", "position": { "x": 1471.0441, "y": 1031.8804, "z": -137.91678 } }, { "type": "LOWER_LIP", "position": { "x": 1478.706, "y": 1140.3444, "z": -116.650894 } }, { "type": "MOUTH_LEFT", "position": { "x": 1397.0453, "y": 1074.5051, "z": -10.362965 } }, { "type": "MOUTH_RIGHT", "position": { "x": 1655.8596, "y": 1077.2307, "z": -110.53521 } }, { "type": "MOUTH_CENTER", "position": { "x": 1478.6444, "y": 1084.2994, "z": -116.58564 } }, { "type": "NOSE_BOTTOM_RIGHT", "position": { "x": 1575.067, "y": 946.60516, "z": -132.10355 } }, { "type": "NOSE_BOTTOM_LEFT", "position": { "x": 1396.0128, "y": 944.48035, "z": -52.012077 } }, { "type": "NOSE_BOTTOM_CENTER", "position": { "x": 1470.0845, "y": 970.4061, "z": -139.32004 } }, { "type": "LEFT_EYE_TOP_BOUNDARY", "position": { "x": 1369.846, "y": 731.5155, "z": -18.276585 } }, { "type": "LEFT_EYE_RIGHT_CORNER", "position": { "x": 1429.0255, "y": 758.3745, "z": -23.542086 } }, { "type": "LEFT_EYE_BOTTOM_BOUNDARY", "position": { "x": 1371.9097, "y": 775.1022, "z": -0.9920981 } }, { "type": "LEFT_EYE_LEFT_CORNER", "position": { "x": 1334.5302, "y": 752.3428, "z": 52.589348 } }, { "type": "LEFT_EYE_PUPIL", "position": { "x": 1369.7902, "y": 752.99426, "z": -4.5812535 } }, { "type": "RIGHT_EYE_TOP_BOUNDARY", "position": { "x": 1646.1317, "y": 740.8714, "z": -149.13914 } }, { "type": "RIGHT_EYE_RIGHT_CORNER", "position": { "x": 1722.3821, "y": 765.43964, "z": -130.75653 } }, { "type": "RIGHT_EYE_BOTTOM_BOUNDARY", "position": { "x": 1659.9559, "y": 784.7147, "z": -132.99072 } }, { "type": "RIGHT_EYE_LEFT_CORNER", "position": { "x": 1593.8276, "y": 765.21747, "z": -102.17816 } }, { "type": "RIGHT_EYE_PUPIL", "position": { "x": 1652.9113, "y": 762.5403, "z": -139.53206 } }, { "type": "LEFT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 1354.2014, "y": 642.7664, "z": -27.636467 } }, { "type": "RIGHT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 1653.919, "y": 652.8384, "z": -169.58447 } }, { "type": "LEFT_EAR_TRAGION", "position": { "x": 1359.5302, "y": 899.9487, "z": 427.43317 } }, { "type": "RIGHT_EAR_TRAGION", "position": { "x": 1989.5599, "y": 921.3098, "z": 129.99654 } }, { "type": "FOREHEAD_GLABELLA", "position": { "x": 1487.4016, "y": 680.26874, "z": -130.2485 } }, { "type": "CHIN_GNATHION", "position": { "x": 1492.2446, "y": 1278.0455, "z": -77.825676 } }, { "type": "CHIN_LEFT_GONION", "position": { "x": 1330.9834, "y": 1094.7004, "z": 301.41083 } }, { "type": "CHIN_RIGHT_GONION", "position": { "x": 1897.9647, "y": 1114.2906, "z": 32.6488 } } ], "rollAngle": 1.7871192, "panAngle": -25.329906, "tiltAngle": -0.32616663, "detectionConfidence": 0.8218701, "landmarkingConfidence": 0.5853151, "joyLikelihood": "VERY_LIKELY", "sorrowLikelihood": "VERY_UNLIKELY", "angerLikelihood": "VERY_UNLIKELY", "surpriseLikelihood": "VERY_UNLIKELY", "underExposedLikelihood": "VERY_UNLIKELY", "blurredLikelihood": "VERY_UNLIKELY", "headwearLikelihood": "VERY_UNLIKELY" }, { "boundingPoly": { "vertices": [ { "x": 168, "y": 1305 }, { "x": 793, "y": 1305 }, { "x": 793, "y": 1844 }, { "x": 168, "y": 1844 } ] }, "fdBoundingPoly": { "vertices": [ { "x": 234, "y": 1454 }, { "x": 701, "y": 1454 }, { "x": 701, "y": 1844 }, { "x": 234, "y": 1844 } ] }, "landmarks": [ { "type": "LEFT_EYE", "position": { "x": 355.4812, "y": 1633.7351, "z": -0.00096174295 } }, { "type": "RIGHT_EYE", "position": { "x": 563.05676, "y": 1598.2274, "z": -15.432735 } }, { "type": "LEFT_OF_LEFT_EYEBROW", "position": { "x": 295.2572, "y": 1596.3945, "z": 27.602434 } }, { "type": "RIGHT_OF_LEFT_EYEBROW", "position": { "x": 399.66183, "y": 1574.5125, "z": -34.742764 } }, { "type": "LEFT_OF_RIGHT_EYEBROW", "position": { "x": 489.41595, "y": 1561.8435, "z": -41.881912 } }, { "type": "RIGHT_OF_RIGHT_EYEBROW", "position": { "x": 604.66504, "y": 1553.2301, "z": 2.8025007 } }, { "type": "MIDPOINT_BETWEEN_EYES", "position": { "x": 445.71527, "y": 1603.4773, "z": -46.01044 } }, { "type": "NOSE_TIP", "position": { "x": 458.00195, "y": 1706.4338, "z": -113.76316 } }, { "type": "UPPER_LIP", "position": { "x": 469.05304, "y": 1780.2344, "z": -78.998 } }, { "type": "LOWER_LIP", "position": { "x": 480.0647, "y": 1842.2673, "z": -73.402145 } }, { "type": "MOUTH_LEFT", "position": { "x": 398.64343, "y": 1820.1232, "z": -23.800583 } }, { "type": "MOUTH_RIGHT", "position": { "x": 558.57007, "y": 1797.7144, "z": -36.007656 } }, { "type": "MOUTH_CENTER", "position": { "x": 475.6739, "y": 1809.3279, "z": -68.785324 } }, { "type": "NOSE_BOTTOM_RIGHT", "position": { "x": 519.20447, "y": 1717.9144, "z": -47.30806 } }, { "type": "NOSE_BOTTOM_LEFT", "position": { "x": 410.96085, "y": 1739.2937, "z": -38.647636 } }, { "type": "NOSE_BOTTOM_CENTER", "position": { "x": 464.29404, "y": 1739.8107, "z": -74.77752 } }, { "type": "LEFT_EYE_TOP_BOUNDARY", "position": { "x": 358.2863, "y": 1615.2714, "z": -11.324151 } }, { "type": "LEFT_EYE_RIGHT_CORNER", "position": { "x": 395.53445, "y": 1626.9333, "z": -2.3256185 } }, { "type": "LEFT_EYE_BOTTOM_BOUNDARY", "position": { "x": 355.713, "y": 1645.1017, "z": -3.0947497 } }, { "type": "LEFT_EYE_LEFT_CORNER", "position": { "x": 325.97894, "y": 1637.1458, "z": 19.892412 } }, { "type": "LEFT_EYE_PUPIL", "position": { "x": 357.76205, "y": 1629.1317, "z": -4.846803 } }, { "type": "RIGHT_EYE_TOP_BOUNDARY", "position": { "x": 543.97064, "y": 1589.2532, "z": -26.101141 } }, { "type": "RIGHT_EYE_RIGHT_CORNER", "position": { "x": 586.45276, "y": 1600.4672, "z": -0.70706856 } }, { "type": "RIGHT_EYE_BOTTOM_BOUNDARY", "position": { "x": 560.2284, "y": 1612.6013, "z": -17.874813 } }, { "type": "RIGHT_EYE_LEFT_CORNER", "position": { "x": 515.07983, "y": 1609.0634, "z": -11.378595 } }, { "type": "RIGHT_EYE_PUPIL", "position": { "x": 548.1346, "y": 1602.3792, "z": -20.216436 } }, { "type": "LEFT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 342.54276, "y": 1561.4143, "z": -13.184053 } }, { "type": "RIGHT_EYEBROW_UPPER_MIDPOINT", "position": { "x": 543.37683, "y": 1533.3728, "z": -29.198135 } }, { "type": "LEFT_EAR_TRAGION", "position": { "x": 276.39093, "y": 1762.4656, "z": 228.13643 } }, { "type": "RIGHT_EAR_TRAGION", "position": { "x": 698.24506, "y": 1702.8165, "z": 193.92969 } }, { "type": "FOREHEAD_GLABELLA", "position": { "x": 443.33896, "y": 1564.7924, "z": -45.18563 } }, { "type": "CHIN_GNATHION", "position": { "x": 493.31305, "y": 1928.5846, "z": -57.822914 } }, { "type": "CHIN_LEFT_GONION", "position": { "x": 305.68286, "y": 1868.2653, "z": 135.39107 } }, { "type": "CHIN_RIGHT_GONION", "position": { "x": 685.4797, "y": 1815.4688, "z": 104.89257 } } ], "rollAngle": -7.3906693, "panAngle": -4.5714307, "tiltAngle": 7.181163, "detectionConfidence": 0.7173322, "landmarkingConfidence": 0.5315869, "joyLikelihood": "VERY_UNLIKELY", "sorrowLikelihood": "VERY_UNLIKELY", "angerLikelihood": "VERY_UNLIKELY", "surpriseLikelihood": "VERY_UNLIKELY", "underExposedLikelihood": "VERY_UNLIKELY", "blurredLikelihood": "POSSIBLE", "headwearLikelihood": "VERY_UNLIKELY" } ] } ] }
C#
Antes de testar esta amostra, siga as instruções de configuração do C# no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para C#.
// Specify a Google Cloud Storage uri for the image
// or a publicly accessible HTTP or HTTPS uri.
var image = Image.FromUri(uri);
var client = ImageAnnotatorClient.Create();
var response = client.DetectFaces(image);
int count = 1;
foreach (var faceAnnotation in response)
{
Console.WriteLine("Face {0}:", count++);
Console.WriteLine(" Joy: {0}", faceAnnotation.JoyLikelihood);
Console.WriteLine(" Anger: {0}", faceAnnotation.AngerLikelihood);
Console.WriteLine(" Sorrow: {0}", faceAnnotation.SorrowLikelihood);
Console.WriteLine(" Surprise: {0}", faceAnnotation.SurpriseLikelihood);
}
Go
Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Go.
// detectFaces gets faces from the Vision API for an image at the given file path.
func detectFacesURI(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
image := vision.NewImageFromURI(file)
annotations, err := client.DetectFaces(ctx, image, nil, 10)
if err != nil {
return err
}
if len(annotations) == 0 {
fmt.Fprintln(w, "No faces found.")
} else {
fmt.Fprintln(w, "Faces:")
for i, annotation := range annotations {
fmt.Fprintln(w, " Face", i)
fmt.Fprintln(w, " Anger:", annotation.AngerLikelihood)
fmt.Fprintln(w, " Joy:", annotation.JoyLikelihood)
fmt.Fprintln(w, " Surprise:", annotation.SurpriseLikelihood)
}
}
return nil
}
Java
Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido da API Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Java.
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.FaceAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DetectFacesGcs {
public static void detectFacesGcs() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg";
detectFacesGcs(filePath);
}
// Detects faces in the specified remote image on Google Cloud Storage.
public static void detectFacesGcs(String gcsPath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
for (FaceAnnotation annotation : res.getFaceAnnotationsList()) {
System.out.format(
"anger: %s%njoy: %s%nsurprise: %s%nposition: %s",
annotation.getAngerLikelihood(),
annotation.getJoyLikelihood(),
annotation.getSurpriseLikelihood(),
annotation.getBoundingPoly());
}
}
}
}
}
Node.js
Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Node.js.
// Imports the Google Cloud client libraries
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const bucketName = 'Bucket where the file resides, e.g. my-bucket';
// const fileName = 'Path to file within bucket, e.g. path/to/image.png';
// Performs face detection on the gcs file
const [result] = await client.faceDetection(`gs://${bucketName}/${fileName}`);
const faces = result.faceAnnotations;
console.log('Faces:');
faces.forEach((face, i) => {
console.log(` Face #${i + 1}:`);
console.log(` Joy: ${face.joyLikelihood}`);
console.log(` Anger: ${face.angerLikelihood}`);
console.log(` Sorrow: ${face.sorrowLikelihood}`);
console.log(` Surprise: ${face.surpriseLikelihood}`);
});
PHP
Antes de testar esta amostra, siga as instruções de configuração do PHP no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para PHP.
namespace Google\Cloud\Samples\Vision;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
// $path = 'gs://path/to/your/image.jpg'
function detect_face_gcs($path)
{
$imageAnnotator = new ImageAnnotatorClient();
# annotate the image
$response = $imageAnnotator->faceDetection($path);
$faces = $response->getFaceAnnotations();
# names of likelihood from google.cloud.vision.enums
$likelihoodName = ['UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY',
'POSSIBLE', 'LIKELY', 'VERY_LIKELY'];
printf("%d faces found:" . PHP_EOL, count($faces));
foreach ($faces as $face) {
$anger = $face->getAngerLikelihood();
printf("Anger: %s" . PHP_EOL, $likelihoodName[$anger]);
$joy = $face->getJoyLikelihood();
printf("Joy: %s" . PHP_EOL, $likelihoodName[$joy]);
$surprise = $face->getSurpriseLikelihood();
printf("Surprise: %s" . PHP_EOL, $likelihoodName[$surprise]);
# get bounds
$vertices = $face->getBoundingPoly()->getVertices();
$bounds = [];
foreach ($vertices as $vertex) {
$bounds[] = sprintf('(%d,%d)', $vertex->getX(), $vertex->getY());
}
print('Bounds: ' . join(', ', $bounds) . PHP_EOL);
print(PHP_EOL);
}
$imageAnnotator->close();
}
Python
Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Python.
def detect_faces_uri(uri):
"""Detects faces in the file located in Google Cloud Storage or the web."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
response = client.face_detection(image=image)
faces = response.face_annotations
# Names of likelihood from google.cloud.vision.enums
likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
'LIKELY', 'VERY_LIKELY')
print('Faces:')
for face in faces:
print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in face.bounding_poly.vertices])
print('face bounds: {}'.format(','.join(vertices)))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
Ruby
Antes de testar esta amostra, siga as instruções de configuração do Ruby no Guia de início rápido da Vision: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vision para Ruby.
# image_path = "Google Cloud Storage URI, eg. 'gs://my-bucket/image.png'"
require "google/cloud/vision"
image_annotator = Google::Cloud::Vision.image_annotator
response = image_annotator.face_detection image: image_path
response.responses.each do |res|
res.face_annotations.each do |face|
puts "Joy: #{face.joy_likelihood}"
puts "Anger: #{face.anger_likelihood}"
puts "Sorrow: #{face.sorrow_likelihood}"
puts "Surprise: #{face.surprise_likelihood}"
end
end
gcloud
Para fazer a detecção facial, use o comando gcloud ml vision detect-faces
conforme mostrado no exemplo a seguir:
gcloud ml vision detect-faces gs://cloud-samples-data/vision/face/faces.jpeg
Testar
Teste a detecção facial abaixo. É possível usar a imagem já especificada (gs://cloud-samples-data/vision/face/faces.jpeg
) ou determinar sua própria imagem. Envie a solicitação selecionando Executar.
