ジオタグを使用してローカル ファイルのウェブ アノテーションを検出する

ジオタグを使用して、ローカル ファイルに対してウェブ アノテーション検出を行います。

コードサンプル

Go

このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Go の設定手順を完了してください。詳細については、Vision Go API のリファレンス ドキュメントをご覧ください。

Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


// detectWebGeo detects geographic metadata from the Vision API for an image at the given file path.
func detectWebGeo(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return err
	}

	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return err
	}
	imageContext := &visionpb.ImageContext{
		WebDetectionParams: &visionpb.WebDetectionParams{
			IncludeGeoResults: true,
		},
	}
	web, err := client.DetectWeb(ctx, image, imageContext)
	if err != nil {
		return err
	}

	if len(web.WebEntities) != 0 {
		fmt.Fprintln(w, "Entities:")
		fmt.Fprintln(w, "\tEntity\t\tScore\tDescription")
		for _, entity := range web.WebEntities {
			fmt.Fprintf(w, "\t%-14s\t%-2.4f\t%s\n", entity.EntityId, entity.Score, entity.Description)
		}
	}

	return nil
}

Java

このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vision Java API のリファレンス ドキュメントをご覧ください。

Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageContext;
import com.google.cloud.vision.v1.WebDetectionParams;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class DetectWebEntitiesIncludeGeoResults {

  public static void detectWebEntitiesIncludeGeoResults() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String filePath = "path/to/your/image/file.jpg";
    detectWebEntitiesIncludeGeoResults(filePath);
  }

  // Find web entities given a local image.
  public static void detectWebEntitiesIncludeGeoResults(String filePath) throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      // Read in the local image
      ByteString contents = ByteString.readFrom(new FileInputStream(filePath));

      // Build the image
      Image image = Image.newBuilder().setContent(contents).build();

      // Enable `IncludeGeoResults`
      WebDetectionParams webDetectionParams =
          WebDetectionParams.newBuilder().setIncludeGeoResults(true).build();

      // Set the parameters for the image
      ImageContext imageContext =
          ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build();

      // Create the request with the image, imageContext, and the specified feature: web detection
      AnnotateImageRequest request =
          AnnotateImageRequest.newBuilder()
              .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
              .setImage(image)
              .setImageContext(imageContext)
              .build();

      // Perform the request
      BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request));

      // Display the results
      response.getResponsesList().stream()
          .forEach(
              r ->
                  r.getWebDetection().getWebEntitiesList().stream()
                      .forEach(
                          entity -> {
                            System.out.format("Description: %s%n", entity.getDescription());
                            System.out.format("Score: %f%n", entity.getScore());
                          }));
    }
  }
}

Node.js

このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vision Node.js API のリファレンス ドキュメントをご覧ください。

Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ImageAnnotatorClient();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const fileName = 'Local image file, e.g. /path/to/image.png';

const request = {
  image: {
    source: {
      filename: fileName,
    },
  },
  imageContext: {
    webDetectionParams: {
      includeGeoResults: true,
    },
  },
};

// Detect similar images on the web to a local file
const [result] = await client.webDetection(request);
const webDetection = result.webDetection;
webDetection.webEntities.forEach(entity => {
  console.log(`Score: ${entity.score}`);
  console.log(`Description: ${entity.description}`);
});

PHP

このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある PHP の設定手順を完了してください。詳細については、Vision PHP API のリファレンス ドキュメントをご覧ください。

Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\ImageContext;
use Google\Cloud\Vision\V1\WebDetectionParams;

/**
 * Detect web entities on an image and include the image's geo metadata
 * to improve the quality of the detection.
 *
 * @param string $path Path to the image, e.g. "path/to/your/image.jpg"
 */
function detect_web_with_geo_metadata(string $path)
{
    $imageAnnotator = new ImageAnnotatorClient();

    # enable include geo results
    $params = new WebDetectionParams();
    $params->setIncludeGeoResults(true);
    $imageContext = new ImageContext();
    $imageContext-> setWebDetectionParams($params);

    # annotate the image
    $image = file_get_contents($path);
    $response = $imageAnnotator->webDetection($image, ['imageContext' => $imageContext]);
    $web = $response->getWebDetection();

    if ($web && $web->getWebEntities()->count()) {
        printf('%d web entities found:' . PHP_EOL,
            count($web->getWebEntities()));
        foreach ($web->getWebEntities() as $entity) {
            printf('Description: %s ' . PHP_EOL, $entity->getDescription());
            printf('Score: %f' . PHP_EOL, $entity->getScore());
            print(PHP_EOL);
        }
    }

    $imageAnnotator->close();
}

Python

このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。詳細については、Vision Python API のリファレンス ドキュメントをご覧ください。

Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def web_entities_include_geo_results(path):
    """Detects web annotations given an image, using the geotag metadata
    in the image to detect web entities."""
    from google.cloud import vision

    client = vision.ImageAnnotatorClient()

    with open(path, "rb") as image_file:
        content = image_file.read()

    image = vision.Image(content=content)

    web_detection_params = vision.WebDetectionParams(include_geo_results=True)
    image_context = vision.ImageContext(web_detection_params=web_detection_params)

    response = client.web_detection(image=image, image_context=image_context)

    for entity in response.web_detection.web_entities:
        print(f"\n\tScore      : {entity.score}")
        print(f"\tDescription: {entity.description}")

    if response.error.message:
        raise Exception(
            "{}\nFor more info on error messages, check: "
            "https://cloud.google.com/apis/design/errors".format(response.error.message)
        )

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。