Daten mit Labels exportieren

Wenn das Hinzufügen von Labels abgeschlossen ist, können Sie das mit Annotationen versehene Dataset durch Aufrufen von ExportData in Ihren Google Cloud Storage-Bucket exportieren.

ExportData unterstützt die Rückgabe einer CSV-Datei mit einer Zeile für jede Annotation oder jedes Datenelement. Das erste Feld gibt die ML-Nutzungskategorie dieser Zeile an. Die Standardeinstellung ist UNASSIGNED. ExportData unterstützt auch JSONL-Dateien, bei denen jede Zeile ein Beispiel darstellt, das ein Datenelement und alle Annotationen enthält. Im Folgenden finden Sie Beispiele für die einzelnen Typen.

Bildklassifizierung

  • CSV-Zeile:

    UNASSIGNED,image_url,label_1,label_2,...

  • JSON-Zeile:

    {
    "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",
             }
          }
       }
    }
    ]
    }

Bildbegrenzungsrahmen

  • CSV-Zeile: Jede Zeile enthält Informationen zu einem Begrenzungsrahmen, wobei zur Darstellung jeder Ecke des Rechtecks x- und y-Koordinaten verwendet werden. Mehrere Felder für ein einzelnes Bild befinden sich in separaten Zeilen. Das Zeilenformat ist UNASSIGNED, image_url, label, topleft_x, topleft_y, topright_x, topright_y, bottomright_x, bottomright_y, bottomleft_x, bottomleft_y. Die Koordinaten "topright_x", "topright_y", "downleft_x" und "downleft_y" können leere Strings sein, da sie redundante Informationen darstellen.

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

  • JSON-Zeile: Wenn in "normalizedVertices" keine Koordinate festgelegt ist, hat dieses Feld standardmäßig den Wert 0. Dies gilt auch für koordinatenbasierte Annotationen.

    {
     "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
                } ]
              }
           }
        }
      }
     ]
    }

Bildbegrenzungspolygon, ausgerichteter Begrenzungsrahmen und Polylinie

  • CSV-Zeile: Jeder Punkt im geschlossenen Polygon bzw. in der geschlossenen Polylinie wird durch einen x- und einen y-Wert angegeben und ist vom nächsten Punkt durch zwei leere CSV-Spalten getrennt. Der letzte Punkt wird wieder mit dem ersten Punkt verbunden, sodass ein Polygon entsteht, während es für die Polylinie keinen geschlossenen Zyklus gibt. Jede Linie stellt ein Polygon bzw. eine Polylinie dar.

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

  • JSON-Zeile:

    {
    "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
            }  ]
          }
       }
    }
    }
    ]
    }

Bildsegmentierung

Für die Bildsegmentierung wird nur die JSONL-Ausgabe bereitgestellt.

  • JSON-Zeile: Das Feld "imageBytes" in "imageSegmentationAnnotation" stellt die Segmentierungsmaske für dieses Bild dar. Die Farbe für jedes Label, d. h. für jeden Hund und jede Katze, wird im Feld "annotationColors" dargestellt.
    {
    "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"
       }
    }
    }
    ]
    }

Videoklassifizierung

  • CSV-Zeile:

    UNASSIGNED,video_url,label,segment_start_time,segment_end_time

  • JSON-Zeile:

    {
    "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"
          }
        }
      }
    } ]
    }

Videoobjekterkennung

  • CSV-Zeile: Die vier Punkte sind oben links, oben rechts, unten rechts, unten links. Der zweite und der vierte Punkt sind optional. Jeder Punkt wird durch einen x- und einen y-Wert dargestellt. Jede Zeile enthält genau einen Begrenzungsrahmen.

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

  • JSON-Zeile:

    {
    "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
          } ]
        },
      } ]
    }
    }
    }]}

Videoobjekt-Tracking

  • CSV-Zeile: Die vier Punkte sind oben links, oben rechts, unten rechts, unten links. Der zweite und der vierte Punkt sind optional. Jeder Punkt wird durch einen x- und einen y-Wert dargestellt. Jede Zeile enthält genau einen Begrenzungsrahmen. Jedes Objekt im Video wird durch eine eindeutige Instanz-ID dargestellt.

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

  • JSON-Zeile:

    {
    "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
        }
      } ]
    }
    }
    }]}

Videoereignis

  • CSV-Zeile: Die vier Punkte sind oben links, oben rechts, unten rechts, unten links. Der zweite und der vierte Punkt sind optional. Jeder Punkt wird durch einen x- und einen y-Wert dargestellt. Jede Zeile enthält genau einen Begrenzungsrahmen. Jedes Objekt im Video wird durch eine eindeutige Instanz-ID dargestellt.

    UNASSIGNED,video_url,label,segment_start_time,segment_end_time

  • JSON-Zeile:

    {
    "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
            }
          }
        }
      }
     } ]
    }
    }
    }]}

Textklassifizierung

  • CSV-Zeile:

    UNASSIGNED,text_url,label_l

  • JSON-Zeile:

    {
      "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"
            }
          }
        }
      } ],
    }

Extraktion der Textentität

Für die Extraktion von Textentitäten wird nur eine JSONL-Ausgabe bereitgestellt.

  • JSON-Zeile:
    {
        "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
              }
            }
          }
        } ],
      }

Der Export von Daten mit ExportData ist ein Vorgang mit langer Ausführungszeit. Die API gibt dabei eine Vorgangs-ID zurück. Sie können die Vorgangs-ID verwenden, um GetOperation aufzurufen und später den Status dafür abzurufen.

Web-UI

So exportieren Sie die mit Labels versehenen Daten über die Data Labeling Service-UI:

  1. Öffnen Sie in der Google Cloud Console die Data Labeling Service-UI.

    Auf der Seite Datasets wird der Status zuvor erstellter Datasets für das aktuelle Projekt angezeigt.

  2. Klicken Sie auf den Namen des Datasets, das Sie exportieren möchten. Die Seite Dataset-Detail wird geöffnet.

  3. Klicken Sie im Bereich Datasets mit Label in der Spalte Exportstatus auf EXPORTIEREN.

  4. Geben Sie dann im Dialogfeld Mit Labels versehenes Dataset exportieren den Cloud Storage-Pfad ein, der für die Ausgabedatei verwendet werden soll, und wählen Sie das gewünschte Dateiformat aus.

  5. Klicken Sie auf EXPORTIEREN.

    Auf der Seite Dataset-Detail wird während des Datenexports der Status "In Bearbeitung" angezeigt. Sobald der Vorgang abgeschlossen ist, ist die Exportdatei unter dem angegebenen Cloud Storage-Pfad zu finden.

Befehlszeile

Legen Sie die folgenden Umgebungsvariablen fest:

  1. PROJECT_ID für Ihre Google Cloud-Projekt-ID.
  2. DATASET_ID für die ID Ihres Datasets aus der Antwort, die Sie beim Erstellen des Datasets erhalten haben. Die ID wird am Ende des vollständigen Dataset-Namens angezeigt:

    projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID
  3. ANNOTATED_DATASET_ID für die ID im Ressourcennamen Ihres mit Annotationen versehenen Datasets. Der Ressourcenname hat das folgende Format:

    projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID/annotatedDatasets/ANNOTATED_DATASET_ID
  4. STORAGE_URI für den URI des Cloud Storage-Buckets, in dem die Ergebnisse gespeichert werden sollen.

Für alle Annotationsanfragen – mit Ausnahme der Bildsegmentierung – sieht die curl-Anfrage in etwa so aus:

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"
       }
     }
   }'

Für das Exportieren von Bildsegmentierungsdaten sieht die curl-Anfrage in etwa so aus:

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}"
       }
     }
   }'

Die Ausgabe sollte in etwa so aussehen:

{
  "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

Für dieses Codebeispiel müssen die Python-Clientbibliotheken installiert sein.

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

Für dieses Codebeispiel müssen die Java-Clientbibliotheken installiert sein.
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();
    }
  }
}