라벨 지정된 데이터 내보내기

라벨 지정 작업이 끝나면 ExportData를 호출하여 주석을 단 데이터 세트를 Google Cloud Storage 버킷으로 내보낼 수 있습니다.

ExportData는 주석 또는 데이터 항목별로 행 하나가 있는 .csv 파일 반환을 지원합니다. 첫 번째 필드는 이 행의 ML 사용량 카테고리를 나타내며 기본값은 UNASSIGNED입니다. ExportData는 jsonl 파일도 지원하며 각 행은 데이터 항목과 모든 주석을 포함하는 예시를 나타냅니다. 다음은 각 유형의 예시입니다.

이미지 분류

  • csv 행:

    UNASSIGNED,image_url,label_1,label_2,...

  • json 행:

    {
    "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "imagePayload":{
    "mimeType":"IMAGE_PNG",
    "imageUri":"gs://sample_bucket/image.png"
    },
    "annotations":[
    {
         "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
       "annotationValue":{
          "imageClassificationAnnotation":{
           "annotationSpec":{
                "displayName":"tulip",
             }
          }
       }
    }
    ]
    }

이미지 경계 상자

  • csv 행: 각 행은 하나의 경계 상자에 대한 정보를 포함하여 x,y 좌표를 통해 각 상자의 모서리를 나타냅니다. 단일 이미지에 여러 개의 상자가 있으면 각각 다른 행에 표시됩니다. 행 형식은 UNASSIGNED, image_url, label, topleft_x, topleft_y, topright_x, topright_y, bottomright_x, bottomright_y, bottomleft_x, bottomleft_y입니다. topright_x, topright_y, bottomleft_x, bottomleft_y 좌표는 중복되는 정보를 제공하므로 빈 문자열일 수도 있습니다.

    UNASSIGNED,image_url,label,0.1,0.1,,,0.3,0.3,,

  • json 행: normalizedVertices의 좌표가 설정되지 않은 경우 해당 필드는 기본적으로 0입니다. 좌표 기반 주석에도 적용됩니다.

    {
     "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
     "imagePayload":{
        "mimeType":"IMAGE_PNG",
        "imageUri":"gs://sample_bucket/image.png"
     },
     "annotations":[
        {
             "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
           "annotationValue":{
             "image_bounding_poly_annotation": {
              "annotationSpec": {
                "displayName": "tulip"
              },
              "normalizedBoundingPoly": {
              "normalizedVertices": [ {
                  "x": 0.1,
                  "y": 0.2
                }, {
                  "x": 0.9,
                  "y": 0.9
                } ]
              }
           }
        }
      }
     ]
    }

이미지 경계 다각형, 방향 지정 경계 상자, 폴리라인

  • csv 행: 닫힌 다각형/폴리라인의 각 점은 x,y 점으로 표시하며, 빈 csv 열 2개로 구분합니다. 마지막 쌍은 다각형의 첫 번째 쌍에 다시 연결되지만 폴리라인의 폐쇄된 주기는 없습니다. 각 행은 하나의 다각형/폴리라인을 나타냅니다.

    UNASSIGNED,image_url,label,0.1,0.1,,,0.3,0.3,,,0.6,0.6,,...

  • json 행:

    {
    "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "imagePayload":{
    "mimeType":"IMAGE_PNG",
    "imageUri":"gs://sample_bucket/image.png"
    },
    "annotations":[
    {
         "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
       "annotationValue":{
         "image_bounding_poly_annotation": {
          "annotationSpec": {
            "displayName": "tulip"
          },
          "normalizedBoundingPoly": {
            "normalizedVertices": [ {
              "x": 0.1,
              "y": 0.1
            }, {
              "x": 0.1,
              "y": 0.2
            }, {
              "x": 0.2,
              "y": 0.3
            }  ]
          }
       }
    }
    }
    ]
    }

이미지 세분화

이미지 세분화의 경우 jsonl 출력만 제공됩니다.

  • json 행: imageSegmentationAnnotation의 imageBytes 필드는 해당 이미지의 세분화 마스크를 나타냅니다. 각 라벨(예: 각 강아지와 고양이)의 색상이 annotationColors 필드에 표시됩니다.
    {
    "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "imagePayload":{
    "mimeType":"IMAGE_PNG",
    "imageUri":"gs://sample_bucket/image.png"
    },
    "annotations":[
    {
         "name":"projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
       "annotationValue":{
         "imageSegmentationAnnotation": {
            "annotationColors": [ {
              "key": "rgb(0,0,255)",
              "value": {
                "display_name": "dog"
              }
            }, {
              "key": "rgb(0,255,0)",
              "value": {
                "display_name": "cat"
              }
            } ],
            "mimeType": "IMAGE_JPEG",
            "imageBytes": "/9j/4AAQSkZJRgABAQAAAQABAAD/2"
       }
    }
    }
    ]
    }

동영상 분류

  • csv 행:

    UNASSIGNED,video_url,label,segment_start_time,segment_end_time

  • json 행:

    {
    "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "videoPayload": {
      "mimeType": "VIDEO_MP4",
      "resolution": {
        width: 720,
        height: 360
      }
      "frameRate": 24
    },
    "annotations": [ {
      "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
      "annotationSource": 3,
      "annotationValue": {
        "videoClassificationAnnotation": {
          "timeSegment": {
            "startTimeOffset": {
              "seconds": 10
            },
            "endTimeOffset": {
              "seconds": 20
            }
          },
          "annotationSpec": {
            "displayName": "dog"
          }
        }
      }
    } ]
    }

동영상 객체 감지

  • csv 행: 4개 점은 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래입니다. 두 번째 및 네 번째 점은 선택사항입니다. 각 점은 x,y로 표시합니다. 각 줄에는 경계 상자가 하나씩 포함됩니다.

    UNASSIGNED,video_url,label,timestamp,0.1,0.1,,,0.3,0.3,,

  • json 행:

    {
    "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "videoPayload": {
      "mimeType": "VIDEO_MP4",
      "resolution": {
        width: 720,
        height: 360
      }
      "frameRate": 24
    },
    "annotations": [ {
      "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
      "annotationSource": 3,
      "annotationValue": {
        "videoObjectTrackingAnnotation": {
      "annotationSpec": {
        "displayName": "tulip"
      },
      "timeSegment": {
        "startTimeOffset": {
          "seconds": 10
        },
        "endTimeOffset": {
          "seconds": 10
        }
      },
      "objectTrackingFrames": [ {
        "normalizedBoundingPoly": {
          "normalizedVertices": [ {
            "x": 0.2,
            "y": 0.3
          }, {
            "x": 0.9,
            "y": 0.5
          } ]
        },
      }, {
        "normalizedBoundingPoly": {
          "normalizedVertices": [ {
            "x": 0.3,
            "y": 0.3
          }, {
            "x": 0.5,
            "y": 0.7
          } ]
        },
      } ]
    }
    }
    }]}

동영상 객체 추적

  • csv 행: 4개 점은 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래입니다. 두 번째 및 네 번째 점은 선택사항입니다. 각 점은 x,y로 표시합니다. 각 줄에는 경계 상자가 하나씩 포함됩니다. 동영상의 각 객체는 고유한 instance_id로 표시됩니다.

    UNASSIGNED,video_url,label,instance_id,timestamp,0.1,0.1,,,0.3,0.3,,

  • json 행:

    {
    "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "videoPayload": {
      "mimeType": "VIDEO_MP4",
      "resolution": {
        width: 720,
        height: 360
      }
      "frameRate": 24
    },
    "annotations": [ {
      "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
      "annotationSource": 3,
      "annotationValue": {
        "videoObjectTrackingAnnotation": {
      "annotationSpec": {
        "displayName": "tulip"
      },
      "timeSegment": {
        "startTimeOffset": {
          "seconds": 10
        },
        "endTimeOffset": {
          "seconds": 20
        }
      },
      "objectTrackingFrames": [ {
        "normalizedBoundingPoly": {
          "normalizedVertices": [ {
            "x": 0.2,
            "y": 0.3
          }, {
            "x": 0.9,
            "y": 0.5
          } ]
        },
        "timeOffset": {
          "nanos": 1000000
        }
      }, {
        "normalizedBoundingPoly": {
          "normalizedVertices": [ {
            "x": 0.3,
            "y": 0.3
          }, {
            "x": 0.5,
            "y": 0.7
          } ]
        },
        "timeOffset": {
          "nanos": 84000000
        }
      } ]
    }
    }
    }]}

동영상 이벤트

  • csv 행: 4개 점은 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래입니다. 두 번째 및 네 번째 점은 선택사항입니다. 각 점은 x,y로 표시합니다. 각 줄에는 경계 상자가 하나씩 포함됩니다. 동영상의 각 객체는 고유한 instance_id로 표시됩니다.

    UNASSIGNED,video_url,label,segment_start_time,segment_end_time

  • json 행:

    {
    "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
    "videoPayload": {
      "mimeType": "VIDEO_MP4",
      "resolution": {
        width: 720,
        height: 360
      }
      "frameRate": 24
    },
    "annotations": [ {
      "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/annotation_id",
      "annotationValue": {
        "videoEventAnnotation": {
          "annotationSpec": {
            "displayName": "Callie"
          },
          "timeSegment": {
            "startTimeOffset": {
              "seconds": 123
            },
            "endTimeOffset": {
              "seconds": 150
            }
          }
        }
      }
     } ]
    }
    }
    }]}

텍스트 분류

  • csv 행:

    UNASSIGNED,text_url,label_l

  • json 행:

    {
      "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
      "textPayload": {
        "textContent": "dummy_text_content",
        "textUri": "gs://test_bucket/file.txt",
        "wordCount": 1
      }
      "annotations": [ {
        "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/fake_annotation_id",
        "annotationValue": {
          "textClassificationAnnotation": {
            "annotationSpec": {
              "displayName": "news"
            }
          }
        }
      } ],
    }

텍스트 항목 추출

텍스트 항목 추출의 경우 jsonl 출력만 제공됩니다.

  • json 행:
    {
        "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id",
        "textPayload": {
          "textContent": "dummy_text_content",
          "textUri": "gs://test_bucket/file.txt",
          "wordCount": 1
        }
        "annotations": [ {
          "name": "projects/project_id/datasets/dataset_id/annotatedDatasets/annotated_dataset_id/examples/example_id/annotations/fake_annotation_id",
          "annotationValue": {
            "textEntityExtractionAnnotation": {
              "annotationSpec": {
                "displayName": "equations"
              },
              "textSegment": {
                "startOffset": 10,
                "endOffset": 20
              }
            }
          }
        } ],
      }

ExportData는 장기 실행 작업입니다. API는 작업 ID를 반환합니다. 작업 ID를 사용하여 GetOperation을 호출해 나중에 상태를 가져올 수 있습니다.

웹 UI

데이터 라벨링 서비스 UI를 사용하여 라벨 지정된 데이터를 내보내려면 다음 단계를 따르세요.

  1. Google Cloud Console에서 데이터 라벨링 서비스 UI를 엽니다.

    데이터 세트 페이지에는 현재 프로젝트에 사용할 수 있는 이전에 작성한 데이터 세트의 상태가 표시됩니다.

  2. 내보낼 데이터 세트의 데이터 세트 이름을 클릭합니다. 그러면 데이터 세트 세부정보 페이지로 이동합니다.

  3. 라벨 지정된 데이터 세트 섹션의 내보내기 상태 열에서 내보내기를 클릭합니다.

  4. 라벨 지정된 데이터 세트 내보내기 대화 상자에서 출력 파일에 사용할 Cloud Storage 경로를 입력하고 원하는 파일 형식을 선택합니다.

  5. 내보내기를 클릭합니다.

    데이터 세트 세부정보 페이지에는 데이터를 내보내는 동안 진행 중 상태가 표시됩니다. 완료되면 지정된 Cloud Storage 경로에서 내보내기 파일을 찾을 수 있습니다.

명령줄

다음 환경 변수를 설정합니다.

  1. PROJECT_ID 변수를 Google Cloud 프로젝트 ID로 설정합니다.
  2. DATASET_ID 변수를 데이터 세트를 만들 때 작성한 응답의 데이터 세트 ID로 설정합니다. ID는 데이터 세트 전체 이름 끝에 표시됩니다.

    projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID
  3. ANNOTATED_DATASET_ID 변수를 주석이 달린 데이터 세트 리소스 이름의 ID로 설정합니다. 리소스 이름의 형식은 다음과 같습니다.

    projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID/annotatedDatasets/ANNOTATED_DATASET_ID
  4. STORAGE_URI 변수를 결과를 저장할 Cloud Storage 버킷의 URI로 설정합니다.

이미지 분할을 제외하는 모든 주석 요청에서 curl 요청은 다음처럼 표시됩니다.

curl -X POST \
   -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
   -H "Content-Type: application/json" \
   https://datalabeling.googleapis.com/v1beta1/projects/${PROJECT_ID}/datasets/${DATASET_ID}:exportData \
   -d '{
     "annotatedDataset": "${ANNOTATED_DATASET_ID}",
     "outputConfig": {
       "gcsDestination": {
           "output_uri": "${STORAGE_URI}",
           "mimeType": "text/csv"
       }
     }
   }'

이미지 분할 데이터를 내보낼 때 curl 요청은 다음처럼 표시됩니다.

curl -X POST \
   -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
   -H "Content-Type: application/json" \
   https://datalabeling.googleapis.com/v1beta1/projects/${PROJECT_ID}/datasets/${DATASET_ID}:exportData \
   -d '{
     "annotatedDataset": "${ANNOTATED_DATASET_ID}",
     "outputConfig": {
       "gcsFolderDestination": {
         "output_folder_uri": "${STORAGE_URI}"
       }
     }
   }'

다음과 비슷한 출력이 표시됩니다.

{
  "name": "projects/data-labeling-codelab/operations/5c73dd6b_0000_2b34_a920_883d24fa2064",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.data-labeling.v1beta1.ExportDataOperationResponse",
    "dataset": "projects/data-labeling-codelab/datasets/5c73db3d_0000_23e0_a25b_94eb2c119c4c"
  }
}

Python

이 코드 예시를 실행하려면 우선 Python 클라이언트 라이브러리를 설치해야 합니다.

def export_data(dataset_resource_name, annotated_dataset_resource_name, export_gcs_uri):
    """Exports a dataset from the given Google Cloud project."""
    from google.cloud import datalabeling_v1beta1 as datalabeling

    client = datalabeling.DataLabelingServiceClient()

    gcs_destination = datalabeling.GcsDestination(
        output_uri=export_gcs_uri, mime_type="text/csv"
    )

    output_config = datalabeling.OutputConfig(gcs_destination=gcs_destination)

    response = client.export_data(
        request={
            "name": dataset_resource_name,
            "annotated_dataset": annotated_dataset_resource_name,
            "output_config": output_config,
        }
    )

    print(f"Dataset ID: {response.result().dataset}\n")
    print("Output config:")
    print("\tGcs destination:")
    print(
        "\t\tOutput URI: {}\n".format(
            response.result().output_config.gcs_destination.output_uri
        )
    )

Java

이 코드 예시를 실행하려면 우선 자바 클라이언트 라이브러리를 설치해야 합니다.
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.datalabeling.v1beta1.DataLabelingServiceClient;
import com.google.cloud.datalabeling.v1beta1.DataLabelingServiceSettings;
import com.google.cloud.datalabeling.v1beta1.ExportDataOperationMetadata;
import com.google.cloud.datalabeling.v1beta1.ExportDataOperationResponse;
import com.google.cloud.datalabeling.v1beta1.ExportDataRequest;
import com.google.cloud.datalabeling.v1beta1.GcsDestination;
import com.google.cloud.datalabeling.v1beta1.LabelStats;
import com.google.cloud.datalabeling.v1beta1.OutputConfig;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;

class ExportData {

  // Export data from an annotated dataset.
  static void exportData(String datasetName, String annotatedDatasetName, String gcsOutputUri)
      throws IOException {
    // String datasetName = DataLabelingServiceClient.formatDatasetName(
    //     "YOUR_PROJECT_ID", "YOUR_DATASETS_UUID");
    // String annotatedDatasetName = DataLabelingServiceClient.formatAnnotatedDatasetName(
    //     "YOUR_PROJECT_ID",
    //     "YOUR_DATASET_UUID",
    //     "YOUR_ANNOTATED_DATASET_UUID");
    // String gcsOutputUri = "gs://YOUR_BUCKET_ID/export_path";

    DataLabelingServiceSettings settings =
        DataLabelingServiceSettings.newBuilder()
            .build();
    try (DataLabelingServiceClient dataLabelingServiceClient =
        DataLabelingServiceClient.create(settings)) {
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUri(gcsOutputUri).setMimeType("text/csv").build();

      OutputConfig outputConfig =
          OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      ExportDataRequest exportDataRequest =
          ExportDataRequest.newBuilder()
              .setName(datasetName)
              .setOutputConfig(outputConfig)
              .setAnnotatedDataset(annotatedDatasetName)
              .build();

      OperationFuture<ExportDataOperationResponse, ExportDataOperationMetadata> operation =
          dataLabelingServiceClient.exportDataAsync(exportDataRequest);

      ExportDataOperationResponse response = operation.get();

      System.out.format("Exported item count: %d\n", response.getExportCount());
      LabelStats labelStats = response.getLabelStats();
      Set<Entry<String, Long>> entries = labelStats.getExampleCountMap().entrySet();
      for (Entry<String, Long> entry : entries) {
        System.out.format("\tLabel: %s\n", entry.getKey());
        System.out.format("\tCount: %d\n\n", entry.getValue());
      }
    } catch (IOException | InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
  }
}