すべてのプロダクト
Search
ドキュメントセンター

Content Moderation:OCR

最終更新日:Jan 08, 2025

このトピックでは、Java 用 Content Moderation SDK を使用して光学式文字認識 (OCR) を実行する方法について説明します。この方法で、テキストを画像内で認識できます。

前提条件

  • Java の依存関係がインストールされていること。詳細については、インストールをご参照ください。

    説明

    インストール トピックに記載されている Java バージョンを使用して依存関係をインストールする必要があります。そうでない場合、後続の操作呼び出しは失敗します。

  • ローカル画像またはバイナリ画像ストリームを画像モデレーションに送信する場合は、Extension.Uploader ユーティリティクラス をダウンロードしてプロジェクトにインポートします。

同期 OCR タスクの送信

操作

説明

対応リージョン

ImageSyncScanRequest

scenes パラメーターを ocr に設定して同期 OCR タスクを送信し、画像内のテキストを認識します。

  • cn-shanghai

  • cn-beijing

  • cn-shenzhen

  • ap-southeast-1

サンプルコード

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.*;

public class Main {

  public static void main(String[] args) throws Exception {
   /**
     * アリババクラウドアカウントの AccessKey ペアは、すべての API 操作に対する権限を持っています。セキュリティリスクを回避するために、RAM ユーザーを使用して API 操作を呼び出したり、日常の O&M を実行したりすることをお勧めします。
     * 環境変数を取得する一般的な方法:
     * 方法 1:
     *     RAM ユーザーの AccessKey ID を取得します:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
     *     RAM ユーザーの AccessKey シークレットを取得します:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
     * 方法 2:
     *     RAM ユーザーの AccessKey ID を取得します:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
     *     RAM ユーザーの AccessKey シークレットを取得します:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
     */
    DefaultProfile profile = DefaultProfile.getProfile(
        "cn-shanghai",
        "環境変数から RAM ユーザーの AccessKey ID を取得することをお勧めします",
        "環境変数から RAM ユーザーの AccessKey シークレットを取得することをお勧めします");
    DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
    IAcsClient client = new DefaultAcsClient(profile);

    ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
    // 操作のレスポンスフォーマットを指定します。
    imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
    // リクエストメソッドを指定します。
    imageSyncScanRequest.setMethod(MethodType.POST);
    imageSyncScanRequest.setEncoding("utf-8");
    // HTTP と HTTPS の両方がサポートされています。
    imageSyncScanRequest.setProtocol(ProtocolType.HTTP);

    JSONObject httpBody = new JSONObject();
    /**
    * モデレーションシナリオを指定します。
    * scenes パラメーターの値 ocr は、サーバーが OCR を使用して画像内のテキストをモデレートすることを示します。
    */
    httpBody.put("scenes", Arrays.asList("ocr"));

        /**
         * モデレートする画像ごとに 1 つのタスクを作成します。
         * リクエストで複数の画像をモデレートする場合、サーバーがリクエストの処理に費やす合計応答時間は、リクエストが開始されたときに開始し、最後の画像のモデレーション時に終了します。
         * リクエストで複数の画像をモデレートする場合の平均応答時間は、単一画像をモデレートする場合よりも長くなります。一度に送信する画像が多いほど、平均応答時間が長くなる可能性が高くなります。
         * この例では、単一画像がモデレートされます。一度に複数の画像をモデレートする必要がある場合は、モデレートする画像ごとに 1 つのタスクを作成します。
         */
    JSONObject task = new JSONObject();
    task.put("dataId", UUID.randomUUID().toString());

    // 画像 URL を指定します。
    task.put("url", "https://example.com/xxx.jpg");
    httpBody.put("tasks", Arrays.asList(task));

    imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()), "UTF-8", FormatType.JSON);
    /**
    * 接続タイムアウト期間と読み取りタイムアウト期間を設定します。サーバーが画像モデレーションリクエストを完了するためのタイムアウト期間は 10 秒です。この期間に基づいてタイムアウトを指定します。
    * 読み取りタイムアウトを 10 秒より短い期間に設定すると、リクエスト処理中にサーバーが読み取りタイムアウトエラーを生成する可能性があります。
    */
    imageSyncScanRequest.setConnectTimeout(3000);
    imageSyncScanRequest.setReadTimeout(10000);
    HttpResponse httpResponse = null;
    try {
      httpResponse = client.doAction(imageSyncScanRequest);
    } catch (ServerException e) {
      e.printStackTrace();
    } catch (ClientException e) {
      e.printStackTrace();
    } catch (Exception e){
      e.printStackTrace();
    }

    // サーバーがリクエストを受信して処理した後に返される結果。
    if(httpResponse != null && httpResponse.isSuccess()){
      JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
      System.out.println(JSON.toJSONString(scrResponse));
      int requestCode = scrResponse.getIntValue("code");
      // すべての画像のモデレーション結果。
      JSONArray taskResults = scrResponse.getJSONArray("data");
      if (200 == requestCode) {
        for (Object taskResult : taskResults) {
          // 単一画像のモデレーション結果。
          int taskCode = ((JSONObject)taskResult).getIntValue("code");
          // 対応するモデレーションシナリオにおける画像のモデレーション結果。リクエストで複数のモデレーションシナリオを指定した場合、各シナリオにおける画像のモデレーション結果が返されます。
          JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
          if(200 == taskCode){
            for (Object sceneResult : sceneResults) {
              String scene = ((JSONObject)sceneResult).getString("scene");
              String suggestion = ((JSONObject)sceneResult).getString("suggestion");
              //何らかの処理を行います
              // モデレートされた画像内のテキスト。
              if("review" .equals(suggestion) && "ocr".equals(scene)){
                JSONObject idCardInfo = ((JSONObject) sceneResult).getJSONObject("idCardInfo");
                System.out.println(idCardInfo.toJSONString());
              }
            }
          }else{
            // 単一画像のモデレートに失敗しました。実際の状況に基づいて障害を分析します。
            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
          }
        }
      } else {
        /**
        * リクエストの処理に失敗しました。実際の状況に基づいて障害を分析します。
        */
        System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
      }
    }
  }
}