在请求中添加SafeSearch参数,主要是指在使用Google Cloud Vision API进行图像内容审核时,通过设置SafeSearch参数来控制返回的图片内容是否包含色情、暴力等敏感信息。以下是在不同编程语言中如何添加SafeSearch参数的示例。
使用Google Cloud Vision API的Python客户端库时,可以通过设置safe_search_detection_config
参数来添加SafeSearch功能。
from google.cloud import vision
from google.cloud.vision_v1 import types
client = vision.ImageAnnotatorClient()
image = types.Image(content=b'your_image_content')
features = [
types.Feature(type_=vision.enums.Feature.Type.SAFE_SEARCH_DETECTION),
]
request = types.AnnotateImageRequest(
image=image,
features=features,
image_context=types.ImageContext(safe_search_detection_config=types.SafeSearchDetectionConfig(level='HIGH'))
)
response = client.annotate_image(request)
safe_search_result = response.safe_search_annotation
print(safe_search_result.label_annotations)
在Java中,可以通过设置ImageContext
的safeSearchDetectionConfig
属性来添加SafeSearch功能。
import com.google.cloud.vision.v1.*;
import com.google.protobuf.ByteString;
public class SafeSearchExample {
public static void main(String[] args) throws Exception {
ImageAnnotatorClient vision = ImageAnnotatorClient.create();
ByteString imgBytes = ByteString.readFrom(new FileInputStream("path/to/your/image.jpg"));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
.setImageContext(ImageContext.newBuilder()
.setSafeSearchDetectionConfig(SafeSearchDetectionConfig.newBuilder().setLevel(SafeSearchDetectionConfig.Level.HIGH).build())
.build())
.build();
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(Arrays.asList(request));
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
System.out.println(annotation.getLabelAnnotationsList());
}
vision.close();
}
}
在Node.js中,可以通过设置imageContext
的safeSearchDetectionConfig
属性来添加SafeSearch功能。
const { ImageAnnotatorClient } = require('@google-cloud/vision');
async function detectSafeSearch() {
const client = new ImageAnnotatorClient();
const [result] = await client
.safeSearchDetection('path/to/your/image.jpg')
.then(responses => {
const annotation = responses[0].safeSearchAnnotation;
console.log(annotation);
})
.catch(err => {
console.error('ERROR:', err);
});
client.close();
}
detectSafeSearch();
在上述示例中,SAFE_SEARCH_DETECTION_CONFIG
的level
参数可以设置为以下值之一:
NONE
: 不进行安全搜索检测。LOW
: 进行基本的安全搜索检测。MEDIUM
: 进行中等程度的安全搜索检测。HIGH
: 进行高级别的安全搜索检测。选择合适的级别可以平衡检测的敏感度和误报率。
领取专属 10元无门槛券
手把手带您无忧上云