A detecção de veículos identifica veículos e placas em imagens armazenadas em buckets do OSS. Para cada veículo detectado, a resposta retorna o tipo, a cor e a localização, além do texto e da posição da placa associada.
Casos de uso
Gestão de tráfego: Utilize este recurso em sistemas de monitoramento e gestão de tráfego, como na identificação de imagens de infrações, para auxiliar no processamento dessas ocorrências.
Identificação de veículos anômalos: Processe imagens enviadas para buckets do OSS para identificar informações sobre veículos e placas.
Análise de tráfego: Analise padrões de uso das vias e a distribuição do tráfego com base em imagens coletadas em zonas monitoradas.
Pré-requisitos
Antes de começar, verifique se você tem:
O serviço Intelligent Media Management (IMM) ativado
Um bucket do OSS criado com as imagens de destino já enviadas
Um projeto IMM criado e vinculado ao bucket — pelo console do OSS ou pela API — na mesma região do bucket
As permissões necessárias concedidas à sua conta
Detectar veículos em uma imagem
Todos os exemplos usam a ação de processamento image/cars, transmitida pelo parâmetro x-oss-process da operação GetObject.
Python
Requer o OSS SDK for Python 2.18.4 ou posterior.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code,
# make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located.
# Example: if the bucket is in the China (Hangzhou) region, use https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the ID of the Alibaba Cloud region in which the bucket is located.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# If the image is stored in the root directory of the bucket, enter the image name.
# If the image is not stored in the root directory, specify the full path. Example: exampledir/example.jpg.
key = 'example.jpg'
# Submit a vehicle detection request using the image/cars processing action.
process = 'image/cars'
try:
result = bucket.get_object(key, process=process)
# Read and print the detection results.
image_cars = result.read().decode('utf-8')
print("Image Cars:")
print(image_cars)
except oss2.exceptions.OssError as e:
print("Error:", e)
Java
Requer o OSS SDK for Java 3.17.4 ou posterior.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Demo1 {
public static void main(String[] args) throws ClientException, ClientException {
// Specify the endpoint of the region in which the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain access credentials from environment variables. Before you run the sample code,
// make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket.
String bucketName = "examplebucket";
// If the image is stored in the root directory of the bucket, enter the image name.
// If the image is not stored in the root directory, specify the full path. Example: exampledir/example.jpg.
String key = "example.jpg";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Submit a vehicle detection request using the image/cars processing action.
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
getObjectRequest.setProcess("image/cars");
OSSObject ossObject = ossClient.getObject(getObjectRequest);
// Read and print the detection results.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = ossObject.getObjectContent().read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
String imageCars = baos.toString("UTF-8");
System.out.println("Image Cars:");
System.out.println(imageCars);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
// Release resources when the OSSClient is no longer needed.
ossClient.shutdown();
}
}
}
Go
Requer o OSS SDK for Go 3.0.2 ou posterior.
package main
import (
"fmt"
"io"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the sample code,
// make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint and region of the bucket. Example: cn-hangzhou.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
bucket, err := client.Bucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Submit a vehicle detection request using the image/cars processing action.
// If the image is not in the root directory, specify the full path. Example: exampledir/example.jpg.
body, err := bucket.GetObject("example.jpg", oss.Process("image/cars"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
defer body.Close()
// Read and print the detection results.
data, err := io.ReadAll(body)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("data:", string(data))
}
PHP
Requer o OSS SDK for PHP 2.7.0 ou posterior.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
try {
// Obtain access credentials from environment variables. Before you run the sample code,
// make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located.
// Example: if the bucket is in the China (Hangzhou) region, use https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = 'https://oss-cn-hangzhou.aliyuncs.com';
// Specify the name of the bucket.
$bucket = 'examplebucket';
// If the image is not in the root directory, specify the full path. Example: exampledir/example.jpg.
$key = 'example.jpg';
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the ID of the Alibaba Cloud region in which the bucket is located.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Submit a vehicle detection request using the image/cars processing action.
$options[$ossClient::OSS_PROCESS] = "image/cars";
$result = $ossClient->getObject($bucket, $key, $options);
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
Referência da API
Exemplo de solicitação
GET /example.jpg?x-oss-process=image/cars HTTP/1.1
Host: image-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 21 Jul 2023 08:57:28 GMT
Authorization: SignatureValue
Exemplo de resposta
HTTP/1.1 200 OK
Server: AliyunOSS
Date: Fri, 21 Jul 2023 08:57:30 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 250
Connection: keep-alive
x-oss-request-id: 64BA487A5423BA333952334F
ETag: "2CE2EA370531B7CC1D23BE6015CF5DA5"
Last-Modified: Mon, 10 Jul 2023 13:07:30 GMT
x-oss-object-type: Normal
x-oss-hash-crc64ecma: 13420962247653419692
x-oss-storage-class: Standard
x-oss-ec: 0048-00000104
Content-Disposition: attachment
x-oss-force-download: true
x-oss-server-time: 552
{
"RequestId": "0C299A82-5D32-57DE-B66B-5E2A814C60BA",
"Cars": [
{
"LicensePlates": [
{
"Content": "LuA8***8",
"Boundary": {
"Width": 200,
"Height": 300,
"Left": 10,
"Top": 30
},
"Confidence": 0.789
}
],
"CarType": "van",
"CarTypeConfidence": 0.516,
"CarColor": "white",
"CarColorConfidence": 0.604,
"Boundary": {
"Width": 200,
"Height": 300,
"Left": 10,
"Top": 30
},
"Confidence": 0.999
}
]
}
O corpo da resposta contém os seguintes campos:
|
Campo |
Descrição |
|
|
Identificador exclusivo da solicitação |
|
|
Tipo de veículo, por exemplo, |
|
|
Pontuação de confiança do tipo de veículo (0–1) |
|
|
Cor do veículo |
|
|
Pontuação de confiança da cor do veículo (0–1) |
|
|
Pontuação geral de confiança da detecção (0–1) |
|
|
Caixa delimitadora do veículo: |
|
|
Texto da placa (parcialmente mascarado para privacidade) |
|
|
Pontuação de confiança da leitura da placa (0–1) |
|
|
Caixa delimitadora da placa: |
Para obter o esquema completo da resposta, consulte DetectImageCars.
Faturamento
A detecção de veículos gera cobranças tanto no OSS quanto no IMM.
No OSS (Preços do OSS):
|
API |
Item de faturamento |
Descrição |
|
GetObject |
Solicitações GET |
Cobrado por solicitação bem-sucedida |
|
GetObject |
Tráfego de saída pela Internet |
Cobrado ao usar um endpoint público (por exemplo, |
|
GetObject |
Recuperação de objetos IA |
Cobrado com base no tamanho dos dados de Acesso Infrequente (IA) recuperados |
|
GetObject |
Aceleração de transferência |
Cobrado ao usar um endpoint de aceleração |
|
HeadObject |
Solicitações GET |
Cobrado por solicitação bem-sucedida |
No IMM (Itens de faturamento do IMM):
|
API |
Item de faturamento |
Descrição |
|
DetectImageCars |
ImageDetect |
Cobrado por solicitação bem-sucedida |
A partir das 11:00 (UTC+8) de 28 de julho de 2025, o serviço de detecção de veículos do IMM passou de gratuito para pago. O item de faturamento aplicável é ImageDetect. Para mais detalhes, consulte o Aviso de ajuste de faturamento do IMM.
Limitações
A detecção de veículos oferece suporte apenas ao processamento síncrono (
x-oss-process).O acesso anônimo não é permitido.