La fonctionnalité d'évaluation de la qualité des images analyse la qualité visuelle d'une image à l'aide de plusieurs métriques, telles que la résolution, le bruit, la distorsion, la saturation des couleurs et l'exposition. Elle fournit un score global indiquant la qualité de l'image. Utilisez cette fonction pour sélectionner une image de couverture ou une vignette vidéo de haute qualité, supprimer les doublons et filtrer les images de faible qualité. Cette rubrique décrit les paramètres et fournit des exemples d'utilisation de l'évaluation de la qualité des images.
Cas d'utilisation
Sélection d'images de couverture pour documents : l'évaluation de la qualité aide les créateurs de contenu à choisir des visuels attractifs et de haute qualité, favorisant ainsi un taux de clics élevé et augmentant le nombre de visites.
Choix de vignettes vidéo : cette fonction permet aux créateurs de vidéos de sélectionner des images percutantes pour servir de miniatures, améliorant l'expérience utilisateur et stimulant les clics.
Filtrage des images de mauvaise qualité : dans les systèmes de traitement et de stockage, les images floues, distordues ou bruitées occupent inutilement de l'espace et dégradent les performances. L'évaluation automatique de la qualité permet de les écarter, optimisant ainsi la pertinence et l'utilité de votre bibliothèque d'images.
Prérequis
Activez le service Intelligent Media Management (IMM). Pour plus d'informations, consultez la rubrique Activer IMM.
Associez un bucket Object Storage Service (OSS) à votre projet Intelligent Media Management (IMM). Pour savoir comment associer un projet IMM à un bucket OSS via la console OSS, reportez-vous à la section Prise en main. Si vous souhaitez effectuer cette association par appel d'API, consultez la documentation de l'opération AttachOSSBucket.
Remarques importantes
L'évaluation de la qualité des images prend uniquement en charge le traitement synchrone (x-oss-process).
L'accès anonyme est refusé.
Des autorisations spécifiques sont requises pour utiliser cette fonctionnalité. Pour en savoir plus, consultez la page relative aux autorisations.
Paramètres
Action : image/score
Pour obtenir la liste des paramètres de réponse, consultez la documentation de l'opération DetectImageScore.
Exemples
Utiliser les SDK OSS
Les extraits de code suivants illustrent comment récupérer le score de qualité d'une image à l'aide des SDK OSS pour les langages de programmation courants. Adaptez ces exemples si vous utilisez un autre langage.
Java
Le SDK OSS pour Java version 3.17.4 ou ultérieure est requis.
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 Demo {
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 region of the bucket in which the image is stored. Example: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain a credential from the 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 of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
String key = "example.jpg";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create an image quality assessment instruction.
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
getObjectRequest.setProcess("image/score");
// Use the process parameter of the getObject method to pass the processing instruction.
OSSObject ossObject = ossClient.getObject(getObjectRequest);
// Read and display the query 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 imageScore = baos.toString("UTF-8");
System.out.println("Image Score:");
System.out.println(imageScore);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
// Stop the OSSClient instance.
ossClient.shutdown();
}
}
}
Python
Le SDK OSS pour Python version 2.18.4 ou ultérieure est requis.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain a credential from the 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. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to 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 of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
key = 'example.jpg'
# Create an image quality assessment instruction.
process = 'image/score'
try:
# Use the get_object method and pass the processing instruction by using the process parameter.
result = bucket.get_object(key, process=process)
# Read and display the query results.
image_score = result.read().decode('utf-8')
print("Image Score:")
print(image_score)
except oss2.exceptions.OssError as e:
print("Error:", e)
Go
Le SDK OSS pour Go version 3.0.2 ou ultérieure est requis.
package main
import (
"fmt"
"io"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain a temporary credential from the 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 of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// Specify the ID of the Alibaba Cloud region in which the bucket is located. 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)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 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 of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
// Create an image quality assessment instruction by using the oss.Process method.
body, err := bucket.GetObject("example.jpg", oss.Process("image/score"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
defer body.Close()
data, err := io.ReadAll(body)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("data:", string(data))
}
PHP
Le SDK OSS pour PHP version 2.7.0 ou ultérieure est requis.
<?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 a credential from the 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. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = 'https://oss-cn-hangzhou.aliyuncs.com';
// Specify the name of the bucket. Example: examplebucket.
$bucket = '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 of the bucket, you must specify the full path of the image. 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);
// Create an image quality assessment instruction.
$options[$ossClient::OSS_PROCESS] = "image/score";
$result = $ossClient->getObject($bucket,$key,$options);
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
Utiliser l'API RESTful
Si votre scénario nécessite un niveau élevé de personnalisation, appelez directement les API RESTful. Cela implique d'intégrer le calcul de signature dans votre code. Pour savoir comment calculer l'en-tête Authorization, reportez-vous à la section (Recommandé) Inclure une signature V4.
Traitez les images en spécifiant le paramètre x-oss-process dans la requête GetObject. Pour plus de détails, consultez la documentation de l'opération GetObject.
Exemple de requête
GET /example.jpg?x-oss-process=image/score HTTP/1.1
Host: image-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 21 Jul 2023 08:28:33 GMT
Authorization: SignatureValue
Exemple de réponse
HTTP/1.1 200 OK
Server: AliyunOSS
Date: Fri, 21 Jul 2023 08:28:34 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 96
Connection: keep-alive
x-oss-request-id: 64BA41B2F326DB30370FEBC9
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: 466
{
"ImageScore":
{
"OverallQualityScore":0.705
},
"RequestId":"E4B48BE7-46D9-589D-AB6D-C16E9A09A075"
}