Video Intelligence API는 LABEL_DETECTION 기능을 사용하여 동영상에 표시되는 항목을 식별할 수 있습니다. 이 기능은 객체, 위치, 활동, 동물 종, 제품 등을 식별합니다.
분석을 다음과 같이 구획화할 수 있습니다.
- 프레임 수준:
각 프레임 내에서 항목이 식별되고 라벨로 지정됩니다(초당 1프레임 샘플링). - 장면 수준:
모든 세그먼트(또는 동영상) 내에서 장면이 자동으로 감지됩니다. 그런 후 항목이 식별되고 각 장면 내에서 라벨로 지정됩니다. - 세그먼트 수준:
주석 목적에 따라 시작 및 종료 타임스탬프를 규정하여 사용자가 선택한 동영상 세그먼트를 분석하도록 지정할 수 있습니다(VideoSegment 참조). 그런 후 항목이 식별되고 각 세그먼트 내에서 라벨로 지정됩니다. 세그먼트를 지정하지 않으면 전체 동영상이 하나의 세그먼트로 취급됩니다.
로컬 파일에 주석 추가
다음은 로컬 파일에서 동영상 라벨 분석을 수행하는 예입니다.
자세한 정보를 알고 싶다면 자세한 Python 가이드를 참조하세요.
REST
프로세스 요청 전송
다음은 videos:annotate
메서드에 POST
요청을 보내는 방법을 보여줍니다. LabelDetectionMode
를 장면 수준 또는 프레임 수준 주석으로 구성할 수 있습니다. SHOT_AND_FRAME_MODE
를 사용하는 것이 좋습니다. 이 예시에서는 Google Cloud CLI를 사용하는 프로젝트의 서비스 계정을 설정하기 위해 액세스 토큰을 사용합니다. Google Cloud CLI 설치, 서비스 계정으로 프로젝트 설정, 액세스 토큰 획득 방법은 Video Intelligence 빠른 시작을 참조하세요.
요청 데이터를 사용하기 전에 다음을 바꿉니다.
- BASE64_ENCODED_CONTENT: base64로 인코딩된 동영상 데이터입니다. 데이터를 base64로 변환하는 방법 안내를 참조하세요.
- PROJECT_NUMBER: Google Cloud 프로젝트의 숫자 식별자
HTTP 메서드 및 URL:
POST https://videointelligence.googleapis.com/v1/videos:annotate
JSON 요청 본문:
{ "inputContent": "BASE64_ENCODED_CONTENT", "features": ["LABEL_DETECTION"], }
요청을 보내려면 다음 옵션 중 하나를 펼칩니다.
cURL(Linux, macOS, Cloud Shell)
요청 본문을 request.json
파일에 저장하고 다음 명령어를 실행합니다.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://videointelligence.googleapis.com/v1/videos:annotate"
PowerShell(Windows)
요청 본문을 request.json
파일에 저장하고 다음 명령어를 실행합니다.
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://videointelligence.googleapis.com/v1/videos:annotate" | Select-Object -Expand Content
다음과 비슷한 JSON 응답이 표시됩니다.
{ "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID" }
요청이 성공하면 Video Intelligence가 작업의 이름을 반환합니다.
결과 가져오기
요청 결과를 가져오려면 projects.locations.operations
리소스에 GET
요청을 보내야 합니다. 다음은 이러한 요청을 전송하는 방법을 보여줍니다.
요청 데이터를 사용하기 전에 다음을 바꿉니다.
- OPERATION_NAME: Video Intelligence API로 반환되는 작업의 이름입니다. 작업 이름은
projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID
형식입니다. - PROJECT_NUMBER: Google Cloud 프로젝트의 숫자 식별자
HTTP 메서드 및 URL:
GET https://videointelligence.googleapis.com/v1/OPERATION_NAME
요청을 보내려면 다음 옵션 중 하나를 펼칩니다.
cURL(Linux, macOS, Cloud Shell)
다음 명령어를 실행합니다.
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER" \
"https://videointelligence.googleapis.com/v1/OPERATION_NAME"
PowerShell(Windows)
다음 명령어를 실행합니다.
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://videointelligence.googleapis.com/v1/OPERATION_NAME" | Select-Object -Expand Content
다음과 비슷한 JSON 응답이 표시됩니다.
대응
{ "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID", "metadata": { "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoProgress", "annotationProgress": [ { "progressPercent": 100, "startTime": "2019-03-12T19:36:09.110351Z", "updateTime": "2019-03-12T19:36:17.519069Z" } ] }, "done": true, "response": { "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoResponse", "annotationResults": [ { "segmentLabelAnnotations": [ { "entity": { "entityId": "/m/01prls", "description": "land vehicle", "languageCode": "en-US" }, "categoryEntities": [ { "entityId": "/m/07yv9", "description": "vehicle", "languageCode": "en-US" } ], "segments": [ { "segment": { "startTimeOffset": "0s", "endTimeOffset": "38.757872s" }, "confidence": 0.6614419 } ] }, { "entity": { "entityId": "/m/039jbq", "description": "urban area", "languageCode": "en-US" }, "categoryEntities": [ { "entityId": "/m/01n32", "description": "city", "languageCode": "en-US" } ], "segments": [ { "segment": { "startTimeOffset": "0s", "endTimeOffset": "38.757872s" }, "confidence": 0.92337775 } ] }, ...
Go
func label(w io.Writer, file string) error {
ctx := context.Background()
client, err := video.NewClient(ctx)
if err != nil {
return fmt.Errorf("video.NewClient: %w", err)
}
defer client.Close()
fileBytes, err := ioutil.ReadFile(file)
if err != nil {
return err
}
op, err := client.AnnotateVideo(ctx, &videopb.AnnotateVideoRequest{
Features: []videopb.Feature{
videopb.Feature_LABEL_DETECTION,
},
InputContent: fileBytes,
})
if err != nil {
return fmt.Errorf("AnnotateVideo: %w", err)
}
resp, err := op.Wait(ctx)
if err != nil {
return fmt.Errorf("Wait: %w", err)
}
printLabels := func(labels []*videopb.LabelAnnotation) {
for _, label := range labels {
fmt.Fprintf(w, "\tDescription: %s\n", label.Entity.Description)
for _, category := range label.CategoryEntities {
fmt.Fprintf(w, "\t\tCategory: %s\n", category.Description)
}
for _, segment := range label.Segments {
start, _ := ptypes.Duration(segment.Segment.StartTimeOffset)
end, _ := ptypes.Duration(segment.Segment.EndTimeOffset)
fmt.Fprintf(w, "\t\tSegment: %s to %s\n", start, end)
}
}
}
// A single video was processed. Get the first result.
result := resp.AnnotationResults[0]
fmt.Fprintln(w, "SegmentLabelAnnotations:")
printLabels(result.SegmentLabelAnnotations)
fmt.Fprintln(w, "ShotLabelAnnotations:")
printLabels(result.ShotLabelAnnotations)
fmt.Fprintln(w, "FrameLabelAnnotations:")
printLabels(result.FrameLabelAnnotations)
return nil
}
Java
// Instantiate a com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
// Read file and encode into Base64
Path path = Paths.get(filePath);
byte[] data = Files.readAllBytes(path);
AnnotateVideoRequest request =
AnnotateVideoRequest.newBuilder()
.setInputContent(ByteString.copyFrom(data))
.addFeatures(Feature.LABEL_DETECTION)
.build();
// Create an operation that will contain the response when the operation completes.
OperationFuture<AnnotateVideoResponse, AnnotateVideoProgress> response =
client.annotateVideoAsync(request);
System.out.println("Waiting for operation to complete...");
for (VideoAnnotationResults results : response.get().getAnnotationResultsList()) {
// process video / segment level label annotations
System.out.println("Locations: ");
for (LabelAnnotation labelAnnotation : results.getSegmentLabelAnnotationsList()) {
System.out.println("Video label: " + labelAnnotation.getEntity().getDescription());
// categories
for (Entity categoryEntity : labelAnnotation.getCategoryEntitiesList()) {
System.out.println("Video label category: " + categoryEntity.getDescription());
}
// segments
for (LabelSegment segment : labelAnnotation.getSegmentsList()) {
double startTime =
segment.getSegment().getStartTimeOffset().getSeconds()
+ segment.getSegment().getStartTimeOffset().getNanos() / 1e9;
double endTime =
segment.getSegment().getEndTimeOffset().getSeconds()
+ segment.getSegment().getEndTimeOffset().getNanos() / 1e9;
System.out.printf("Segment location: %.3f:%.2f\n", startTime, endTime);
System.out.println("Confidence: " + segment.getConfidence());
}
}
// process shot label annotations
for (LabelAnnotation labelAnnotation : results.getShotLabelAnnotationsList()) {
System.out.println("Shot label: " + labelAnnotation.getEntity().getDescription());
// categories
for (Entity categoryEntity : labelAnnotation.getCategoryEntitiesList()) {
System.out.println("Shot label category: " + categoryEntity.getDescription());
}
// segments
for (LabelSegment segment : labelAnnotation.getSegmentsList()) {
double startTime =
segment.getSegment().getStartTimeOffset().getSeconds()
+ segment.getSegment().getStartTimeOffset().getNanos() / 1e9;
double endTime =
segment.getSegment().getEndTimeOffset().getSeconds()
+ segment.getSegment().getEndTimeOffset().getNanos() / 1e9;
System.out.printf("Segment location: %.3f:%.2f\n", startTime, endTime);
System.out.println("Confidence: " + segment.getConfidence());
}
}
// process frame label annotations
for (LabelAnnotation labelAnnotation : results.getFrameLabelAnnotationsList()) {
System.out.println("Frame label: " + labelAnnotation.getEntity().getDescription());
// categories
for (Entity categoryEntity : labelAnnotation.getCategoryEntitiesList()) {
System.out.println("Frame label category: " + categoryEntity.getDescription());
}
// segments
for (LabelSegment segment : labelAnnotation.getSegmentsList()) {
double startTime =
segment.getSegment().getStartTimeOffset().getSeconds()
+ segment.getSegment().getStartTimeOffset().getNanos() / 1e9;
double endTime =
segment.getSegment().getEndTimeOffset().getSeconds()
+ segment.getSegment().getEndTimeOffset().getNanos() / 1e9;
System.out.printf("Segment location: %.3f:%.2f\n", startTime, endTime);
System.out.println("Confidence: " + segment.getConfidence());
}
}
}
}
Node.js
// Imports the Google Cloud Video Intelligence library + Node's fs library
const video = require('@google-cloud/video-intelligence').v1;
const fs = require('fs');
const util = require('util');
// Creates a client
const client = new video.VideoIntelligenceServiceClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const path = 'Local file to analyze, e.g. ./my-file.mp4';
// Reads a local video file and converts it to base64
const readFile = util.promisify(fs.readFile);
const file = await readFile(path);
const inputContent = file.toString('base64');
// Constructs request
const request = {
inputContent: inputContent,
features: ['LABEL_DETECTION'],
};
// Detects labels in a video
const [operation] = await client.annotateVideo(request);
console.log('Waiting for operation to complete...');
const [operationResult] = await operation.promise();
// Gets annotations for video
const annotations = operationResult.annotationResults[0];
const labels = annotations.segmentLabelAnnotations;
labels.forEach(label => {
console.log(`Label ${label.entity.description} occurs at:`);
label.segments.forEach(segment => {
const time = segment.segment;
if (time.startTimeOffset.seconds === undefined) {
time.startTimeOffset.seconds = 0;
}
if (time.startTimeOffset.nanos === undefined) {
time.startTimeOffset.nanos = 0;
}
if (time.endTimeOffset.seconds === undefined) {
time.endTimeOffset.seconds = 0;
}
if (time.endTimeOffset.nanos === undefined) {
time.endTimeOffset.nanos = 0;
}
console.log(
`\tStart: ${time.startTimeOffset.seconds}` +
`.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`
);
console.log(
`\tEnd: ${time.endTimeOffset.seconds}.` +
`${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`
);
console.log(`\tConfidence: ${segment.confidence}`);
});
});
Python
Python용 Video Intelligence API 클라이언트 라이브러리 설치 및 사용에 대한 자세한 내용은 Video Intelligence API 클라이언트 라이브러리를 참조하세요."""Detect labels given a file path."""
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.Feature.LABEL_DETECTION]
with io.open(path, "rb") as movie:
input_content = movie.read()
operation = video_client.annotate_video(
request={"features": features, "input_content": input_content}
)
print("\nProcessing video for label annotations:")
result = operation.result(timeout=90)
print("\nFinished processing.")
# Process video/segment level label annotations
segment_labels = result.annotation_results[0].segment_label_annotations
for i, segment_label in enumerate(segment_labels):
print("Video label description: {}".format(segment_label.entity.description))
for category_entity in segment_label.category_entities:
print(
"\tLabel category description: {}".format(category_entity.description)
)
for i, segment in enumerate(segment_label.segments):
start_time = (
segment.segment.start_time_offset.seconds
+ segment.segment.start_time_offset.microseconds / 1e6
)
end_time = (
segment.segment.end_time_offset.seconds
+ segment.segment.end_time_offset.microseconds / 1e6
)
positions = "{}s to {}s".format(start_time, end_time)
confidence = segment.confidence
print("\tSegment {}: {}".format(i, positions))
print("\tConfidence: {}".format(confidence))
print("\n")
# Process shot level label annotations
shot_labels = result.annotation_results[0].shot_label_annotations
for i, shot_label in enumerate(shot_labels):
print("Shot label description: {}".format(shot_label.entity.description))
for category_entity in shot_label.category_entities:
print(
"\tLabel category description: {}".format(category_entity.description)
)
for i, shot in enumerate(shot_label.segments):
start_time = (
shot.segment.start_time_offset.seconds
+ shot.segment.start_time_offset.microseconds / 1e6
)
end_time = (
shot.segment.end_time_offset.seconds
+ shot.segment.end_time_offset.microseconds / 1e6
)
positions = "{}s to {}s".format(start_time, end_time)
confidence = shot.confidence
print("\tSegment {}: {}".format(i, positions))
print("\tConfidence: {}".format(confidence))
print("\n")
# Process frame level label annotations
frame_labels = result.annotation_results[0].frame_label_annotations
for i, frame_label in enumerate(frame_labels):
print("Frame label description: {}".format(frame_label.entity.description))
for category_entity in frame_label.category_entities:
print(
"\tLabel category description: {}".format(category_entity.description)
)
# Each frame_label_annotation has many frames,
# here we print information only about the first frame.
frame = frame_label.frames[0]
time_offset = frame.time_offset.seconds + frame.time_offset.microseconds / 1e6
print("\tFirst frame time offset: {}s".format(time_offset))
print("\tFirst frame confidence: {}".format(frame.confidence))
print("\n")
추가 언어
C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 Video Intelligence 참조 문서를 참조하세요.
PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Video Intelligence 참조 문서를 참조하세요.
Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Video Intelligence 참조 문서를 참조하세요.
Cloud Storage의 파일에 주석 추가
다음은 Cloud Storage에 있는 파일에서 라벨에 대해 동영상 분석을 수행하는 예시입니다.
REST
Python용 Video Intelligence API 클라이언트 라이브러리 설치 및 사용에 대한 자세한 내용은 Video Intelligence API 클라이언트 라이브러리를 참조하세요.프로세스 요청 전송
다음은 annotate
메서드에 POST
요청을 보내는 방법을 보여줍니다. 이 예시에서는 Google Cloud CLI를 사용하는 프로젝트의 서비스 계정을 설정하기 위해 액세스 토큰을 사용합니다. Google Cloud CLI 설치, 서비스 계정으로 프로젝트 설정, 액세스 토큰 획득 방법은 Video Intelligence 빠른 시작을 참조하세요.
요청 데이터를 사용하기 전에 다음을 바꿉니다.
- INPUT_URI: 파일 이름을 포함하여 주석을 추가하고자 하는 파일을 포함한 Cloud Storage 버킷입니다.
gs://
로 시작해야 합니다. - PROJECT_NUMBER: Google Cloud 프로젝트의 숫자 식별자
HTTP 메서드 및 URL:
POST https://videointelligence.googleapis.com/v1/videos:annotate
JSON 요청 본문:
{ "inputUri": "INPUT_URI", "features": ["LABEL_DETECTION"], }
요청을 보내려면 다음 옵션 중 하나를 펼칩니다.
cURL(Linux, macOS, Cloud Shell)
요청 본문을 request.json
파일에 저장하고 다음 명령어를 실행합니다.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://videointelligence.googleapis.com/v1/videos:annotate"
PowerShell(Windows)
요청 본문을 request.json
파일에 저장하고 다음 명령어를 실행합니다.
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://videointelligence.googleapis.com/v1/videos:annotate" | Select-Object -Expand Content
다음과 비슷한 JSON 응답이 표시됩니다.
{ "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID" }
요청이 성공하면 Video Intelligence가 작업 이름을 반환합니다.
결과 가져오기
요청 결과를 가져오려면 projects.locations.operations
리소스에 GET
요청을 보내야 합니다. 다음은 이러한 요청을 전송하는 방법을 보여줍니다.
요청 데이터를 사용하기 전에 다음을 바꿉니다.
- OPERATION_NAME: Video Intelligence API로 반환되는 작업의 이름입니다. 작업 이름은
projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID
형식입니다. - PROJECT_NUMBER: Google Cloud 프로젝트의 숫자 식별자
HTTP 메서드 및 URL:
GET https://videointelligence.googleapis.com/v1/OPERATION_NAME
요청을 보내려면 다음 옵션 중 하나를 펼칩니다.
cURL(Linux, macOS, Cloud Shell)
다음 명령어를 실행합니다.
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_NUMBER" \
"https://videointelligence.googleapis.com/v1/OPERATION_NAME"
PowerShell(Windows)
다음 명령어를 실행합니다.
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_NUMBER" }
Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://videointelligence.googleapis.com/v1/OPERATION_NAME" | Select-Object -Expand Content
다음과 비슷한 JSON 응답이 표시됩니다.
응답
{ "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID", "metadata": { "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoProgress", "annotationProgress": [ { "inputUri": "INPUT_URI", "progressPercent": 100, "startTime": "2019-11-13T19:25:56.206335Z", "updateTime": "2019-11-13T19:26:16.215615Z" } ] }, "done": true, "response": { "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoResponse", "annotationResults": [ { "inputUri": "INPUT_URI", "segmentLabelAnnotations": [ { "entity": { "entityId": "/m/01vkl", "description": "circle", "languageCode": "en-US" }, "categoryEntities": [ { "entityId": "/m/016nqd", "description": "shape", "languageCode": "en-US" } ], "segments": [ { "segment": { "startTimeOffset": "0s", "endTimeOffset": "16.416666s" }, "confidence": 0.36535457 } ] }, ... ] } ] } }
주석 결과 다운로드
소스에서 대상 버킷으로 주석을 복사합니다(파일 및 객체 복사 참조).
gsutil cp gcs_uri gs://my-bucket
참고: 사용자가 출력 gcs uri를 제공하면 주석이 해당 gcs uri에 저장됩니다.
Go
func labelURI(w io.Writer, file string) error {
ctx := context.Background()
client, err := video.NewClient(ctx)
if err != nil {
return fmt.Errorf("video.NewClient: %w", err)
}
defer client.Close()
op, err := client.AnnotateVideo(ctx, &videopb.AnnotateVideoRequest{
Features: []videopb.Feature{
videopb.Feature_LABEL_DETECTION,
},
InputUri: file,
})
if err != nil {
return fmt.Errorf("AnnotateVideo: %w", err)
}
resp, err := op.Wait(ctx)
if err != nil {
return fmt.Errorf("Wait: %w", err)
}
printLabels := func(labels []*videopb.LabelAnnotation) {
for _, label := range labels {
fmt.Fprintf(w, "\tDescription: %s\n", label.Entity.Description)
for _, category := range label.CategoryEntities {
fmt.Fprintf(w, "\t\tCategory: %s\n", category.Description)
}
for _, segment := range label.Segments {
start, _ := ptypes.Duration(segment.Segment.StartTimeOffset)
end, _ := ptypes.Duration(segment.Segment.EndTimeOffset)
fmt.Fprintf(w, "\t\tSegment: %s to %s\n", start, end)
}
}
}
// A single video was processed. Get the first result.
result := resp.AnnotationResults[0]
fmt.Fprintln(w, "SegmentLabelAnnotations:")
printLabels(result.SegmentLabelAnnotations)
fmt.Fprintln(w, "ShotLabelAnnotations:")
printLabels(result.ShotLabelAnnotations)
fmt.Fprintln(w, "FrameLabelAnnotations:")
printLabels(result.FrameLabelAnnotations)
return nil
}
Java
// Instantiate a com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
// Provide path to file hosted on GCS as "gs://bucket-name/..."
AnnotateVideoRequest request =
AnnotateVideoRequest.newBuilder()
.setInputUri(gcsUri)
.addFeatures(Feature.LABEL_DETECTION)
.build();
// Create an operation that will contain the response when the operation completes.
OperationFuture<AnnotateVideoResponse, AnnotateVideoProgress> response =
client.annotateVideoAsync(request);
System.out.println("Waiting for operation to complete...");
for (VideoAnnotationResults results : response.get().getAnnotationResultsList()) {
// process video / segment level label annotations
System.out.println("Locations: ");
for (LabelAnnotation labelAnnotation : results.getSegmentLabelAnnotationsList()) {
System.out.println("Video label: " + labelAnnotation.getEntity().getDescription());
// categories
for (Entity categoryEntity : labelAnnotation.getCategoryEntitiesList()) {
System.out.println("Video label category: " + categoryEntity.getDescription());
}
// segments
for (LabelSegment segment : labelAnnotation.getSegmentsList()) {
double startTime =
segment.getSegment().getStartTimeOffset().getSeconds()
+ segment.getSegment().getStartTimeOffset().getNanos() / 1e9;
double endTime =
segment.getSegment().getEndTimeOffset().getSeconds()
+ segment.getSegment().getEndTimeOffset().getNanos() / 1e9;
System.out.printf("Segment location: %.3f:%.3f\n", startTime, endTime);
System.out.println("Confidence: " + segment.getConfidence());
}
}
// process shot label annotations
for (LabelAnnotation labelAnnotation : results.getShotLabelAnnotationsList()) {
System.out.println("Shot label: " + labelAnnotation.getEntity().getDescription());
// categories
for (Entity categoryEntity : labelAnnotation.getCategoryEntitiesList()) {
System.out.println("Shot label category: " + categoryEntity.getDescription());
}
// segments
for (LabelSegment segment : labelAnnotation.getSegmentsList()) {
double startTime =
segment.getSegment().getStartTimeOffset().getSeconds()
+ segment.getSegment().getStartTimeOffset().getNanos() / 1e9;
double endTime =
segment.getSegment().getEndTimeOffset().getSeconds()
+ segment.getSegment().getEndTimeOffset().getNanos() / 1e9;
System.out.printf("Segment location: %.3f:%.3f\n", startTime, endTime);
System.out.println("Confidence: " + segment.getConfidence());
}
}
// process frame label annotations
for (LabelAnnotation labelAnnotation : results.getFrameLabelAnnotationsList()) {
System.out.println("Frame label: " + labelAnnotation.getEntity().getDescription());
// categories
for (Entity categoryEntity : labelAnnotation.getCategoryEntitiesList()) {
System.out.println("Frame label category: " + categoryEntity.getDescription());
}
// segments
for (LabelSegment segment : labelAnnotation.getSegmentsList()) {
double startTime =
segment.getSegment().getStartTimeOffset().getSeconds()
+ segment.getSegment().getStartTimeOffset().getNanos() / 1e9;
double endTime =
segment.getSegment().getEndTimeOffset().getSeconds()
+ segment.getSegment().getEndTimeOffset().getNanos() / 1e9;
System.out.printf("Segment location: %.3f:%.2f\n", startTime, endTime);
System.out.println("Confidence: " + segment.getConfidence());
}
}
}
}
Node.js
// Imports the Google Cloud Video Intelligence library
const video = require('@google-cloud/video-intelligence').v1;
// Creates a client
const client = new video.VideoIntelligenceServiceClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const gcsUri = 'GCS URI of the video to analyze, e.g. gs://my-bucket/my-video.mp4';
const request = {
inputUri: gcsUri,
features: ['LABEL_DETECTION'],
};
// Detects labels in a video
const [operation] = await client.annotateVideo(request);
console.log('Waiting for operation to complete...');
const [operationResult] = await operation.promise();
// Gets annotations for video
const annotations = operationResult.annotationResults[0];
const labels = annotations.segmentLabelAnnotations;
labels.forEach(label => {
console.log(`Label ${label.entity.description} occurs at:`);
label.segments.forEach(segment => {
const time = segment.segment;
if (time.startTimeOffset.seconds === undefined) {
time.startTimeOffset.seconds = 0;
}
if (time.startTimeOffset.nanos === undefined) {
time.startTimeOffset.nanos = 0;
}
if (time.endTimeOffset.seconds === undefined) {
time.endTimeOffset.seconds = 0;
}
if (time.endTimeOffset.nanos === undefined) {
time.endTimeOffset.nanos = 0;
}
console.log(
`\tStart: ${time.startTimeOffset.seconds}` +
`.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`
);
console.log(
`\tEnd: ${time.endTimeOffset.seconds}.` +
`${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`
);
console.log(`\tConfidence: ${segment.confidence}`);
});
});
Python
"""Detects labels given a GCS path."""
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.Feature.LABEL_DETECTION]
mode = videointelligence.LabelDetectionMode.SHOT_AND_FRAME_MODE
config = videointelligence.LabelDetectionConfig(label_detection_mode=mode)
context = videointelligence.VideoContext(label_detection_config=config)
operation = video_client.annotate_video(
request={"features": features, "input_uri": path, "video_context": context}
)
print("\nProcessing video for label annotations:")
result = operation.result(timeout=180)
print("\nFinished processing.")
# Process video/segment level label annotations
segment_labels = result.annotation_results[0].segment_label_annotations
for i, segment_label in enumerate(segment_labels):
print("Video label description: {}".format(segment_label.entity.description))
for category_entity in segment_label.category_entities:
print(
"\tLabel category description: {}".format(category_entity.description)
)
for i, segment in enumerate(segment_label.segments):
start_time = (
segment.segment.start_time_offset.seconds
+ segment.segment.start_time_offset.microseconds / 1e6
)
end_time = (
segment.segment.end_time_offset.seconds
+ segment.segment.end_time_offset.microseconds / 1e6
)
positions = "{}s to {}s".format(start_time, end_time)
confidence = segment.confidence
print("\tSegment {}: {}".format(i, positions))
print("\tConfidence: {}".format(confidence))
print("\n")
# Process shot level label annotations
shot_labels = result.annotation_results[0].shot_label_annotations
for i, shot_label in enumerate(shot_labels):
print("Shot label description: {}".format(shot_label.entity.description))
for category_entity in shot_label.category_entities:
print(
"\tLabel category description: {}".format(category_entity.description)
)
for i, shot in enumerate(shot_label.segments):
start_time = (
shot.segment.start_time_offset.seconds
+ shot.segment.start_time_offset.microseconds / 1e6
)
end_time = (
shot.segment.end_time_offset.seconds
+ shot.segment.end_time_offset.microseconds / 1e6
)
positions = "{}s to {}s".format(start_time, end_time)
confidence = shot.confidence
print("\tSegment {}: {}".format(i, positions))
print("\tConfidence: {}".format(confidence))
print("\n")
# Process frame level label annotations
frame_labels = result.annotation_results[0].frame_label_annotations
for i, frame_label in enumerate(frame_labels):
print("Frame label description: {}".format(frame_label.entity.description))
for category_entity in frame_label.category_entities:
print(
"\tLabel category description: {}".format(category_entity.description)
)
# Each frame_label_annotation has many frames,
# here we print information only about the first frame.
frame = frame_label.frames[0]
time_offset = frame.time_offset.seconds + frame.time_offset.microseconds / 1e6
print("\tFirst frame time offset: {}s".format(time_offset))
print("\tFirst frame confidence: {}".format(frame.confidence))
print("\n")
추가 언어
C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 Video Intelligence 참조 문서를 참조하세요.
PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Video Intelligence 참조 문서를 참조하세요.
Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Video Intelligence 참조 문서를 참조하세요.