アニメーション医療グラフィックを放射線システムが理解できる形式に変換することは、開発者にとってボトルネックになることがあります。 Aspose.Slides Cloud SDK for Python は、このタスクを簡素化する強力なライブラリを提供します。このガイドでは、Python での完全な GIF から DICOM への変換例を確認し、認証の設定方法、バッチ処理の扱い方、REST 統合のための同等の cURL 呼び出しについて学びます。

Python を使用して GIF 画像を DICOM ファイルに変換する方法 - ステップバイステップ

  1. 認証の構成と SlidesApi の初期化: クライアント資格情報を設定し、SlidesApi のインスタンスを作成します。
from asposeslidescloud import SlidesApi, Configuration

config = Configuration()
config.api_key['client_id'] = "YOUR_CLIENT_ID"
config.api_key['client_secret'] = "YOUR_CLIENT_SECRET"
slides_api = SlidesApi(configuration=config)

この手順は、Python における GIF から DICOM への変換サンプルの環境を準備します。

  1. 入力フォルダーと出力フォルダーを定義する: ソースGIFと生成されたDICOMファイル用のフォルダーを作成します。
import os

INPUT_FOLDER = "gif_inputs"
OUTPUT_FOLDER = "dicom_outputs"
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
  1. 変換関数を作成する: convert_local を使用して GIF を DICOM に変換し、オプションのメタデータを渡します。
def convert_gif_to_dicom(gif_path: str, dicom_path: str):
    with open(gif_path, "rb") as gif_file:
        result_bytes = slides_api.convert_local(
            file=gif_file,
            format="dicom",
            patientName="John Doe",
            patientId="123456",
            studyDescription="Sample GIF to DICOM conversion"
        )
    with open(dicom_path, "wb") as out_file:
        out_file.write(result_bytes)
  1. すべての GIF ファイルを一括変換: 入力フォルダーをスキャンし、各ファイルに対して変換関数を呼び出します。
import glob

def batch_convert_gif_folder(input_folder: str, output_folder: str):
    gif_files = glob.glob(os.path.join(input_folder, "*.gif"))
    for gif_file in gif_files:
        base_name = os.path.splitext(os.path.basename(gif_file))[0]
        dicom_file = os.path.join(output_folder, f"{base_name}.dcm")
        convert_gif_to_dicom(gif_file, dicom_file)
  1. スクリプトを実行する: モジュールが直接実行されたときにバッチ変換を実行します。
if __name__ == "__main__":
    batch_convert_gif_folder(INPUT_FOLDER, OUTPUT_FOLDER)

スクリプトは、Python での GIF から DICOM への変換例を完了し、すぐに使用できる DICOM ファイルを提供します。

完全なコード例: GIF から DICOM への変換(Aspose.Slides Cloud SDK 使用)

以下のコードは、Python での GIF から DICOM への変換例の完全な実装を示しています。

import os
import glob
from asposeslidescloud import SlidesApi, ApiException, Configuration

# -------------------- Setup Aspose.Slides Cloud SDK and Authentication --------------------
# Replace with your actual Aspose Cloud credentials
CLIENT_ID = "YOUR_CLIENT_ID"
CLIENT_SECRET = "YOUR_CLIENT_SECRET"

config = Configuration()
config.api_key['client_id'] = CLIENT_ID
config.api_key['client_secret'] = CLIENT_SECRET
# Optional: set the base URL if you use a different region
# config.host = "https://api.aspose.cloud"

slides_api = SlidesApi(configuration=config)

# -------------------- Prepare GIF Input and Define DICOM Parameters --------------------
INPUT_FOLDER = "gif_inputs"
OUTPUT_FOLDER = "dicom_outputs"
os.makedirs(OUTPUT_FOLDER, exist_ok=True)

# Example DICOM metadata (if the API supports passing them as query parameters)
# Here we just illustrate the idea; actual parameter names may differ.
dicom_params = {
    "patientName": "John Doe",
    "patientId": "123456",
    "studyDescription": "Sample GIF to DICOM conversion"
}

# -------------------- Write Python Script for GIF to DICOM Conversion Example --------------------
def convert_gif_to_dicom(gif_path: str, dicom_path: str):
    """
    Converts a single GIF file to DICOM format using Aspose.Slides Cloud SDK.
    """
    try:
        # Read the GIF file into memory
        with open(gif_path, "rb") as gif_file:
            # The SDK method `convert_local` returns the converted file bytes.
            # Pass the desired output format ("dicom") and any additional parameters.
            result_bytes = slides_api.convert_local(
                file=gif_file,
                format="dicom",
                # The following dictionary is illustrative; adjust according to SDK docs.
                **dicom_params
            )
        # Write the resulting DICOM bytes to the output file
        with open(dicom_path, "wb") as out_file:
            out_file.write(result_bytes)
        print(f"Converted '{gif_path}' → '{dicom_path}'")
    except ApiException as e:
        print(f"API error while converting '{gif_path}': {e}")
    except Exception as ex:
        print(f"Unexpected error while converting '{gif_path}': {ex}")

# -------------------- Batch Convert GIF Files to DICOM in Python --------------------
def batch_convert_gif_folder(input_folder: str, output_folder: str):
    """
    Scans the input folder for *.gif files and converts each to DICOM,
    storing results in the output folder.
    """
    gif_files = glob.glob(os.path.join(input_folder, "*.gif"))
    if not gif_files:
        print(f"No GIF files found in '{input_folder}'.")
        return

for gif_file in gif_files:
        base_name = os.path.splitext(os.path.basename(gif_file))[0]
        dicom_file = os.path.join(output_folder, f"{base_name}.dcm")
        convert_gif_to_dicom(gif_file, dicom_file)

# -------------------- Execute Batch Conversion --------------------
if __name__ == "__main__":
    batch_convert_gif_folder(INPUT_FOLDER, OUTPUT_FOLDER)

注: このコード例は基本機能を示しています。プロジェクトで使用する前に、ファイルパスや設定値が実際の環境に合わせて更新されていることを確認し、必要な依存関係がすべて正しくインストールされていることを検証し、開発環境で十分にテストしてください。問題が発生した場合は、公式ドキュメント を参照するか、サポートチーム にお問い合わせください。

cURL を使用して Aspose.Slides Cloud 変換エンドポイントを呼び出す

以下は、Python を使用して Aspose.Slides Cloud API で同じ GIF から DICOM への変換例を実行する REST 呼び出しです。

  1. アクセストークンを取得 (プレースホルダーを自分の資格情報に置き換えてください)。
curl -X POST "https://api.aspose.cloud/connect/token" \
     -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
  1. GIF ファイルをアップロード 一時ストレージへ。
curl -X PUT "https://api.aspose.cloud/v3.0/slides/storage/file/gif_inputs/sample.gif" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/octet-stream" \
     --data-binary "@sample.gif"
  1. DICOMへの変換リクエスト オプションのメタデータを渡しながら。
curl -X POST "https://api.aspose.cloud/v3.0/slides/gif_inputs/sample.gif/convert/dicom?patientName=John%20Doe&patientId=123456&studyDescription=Sample%20GIF%20to%20DICOM%20conversion" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o "dicom_outputs/sample.dcm"
  1. 結果の DICOM ファイルをダウンロード (別の場所に保存した場合)。
curl -X GET "https://api.aspose.cloud/v3.0/slides/storage/file/dicom_outputs/sample.dcm" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o "sample.dcm"

リクエスト パラメータの詳細については、API リファレンスをご覧ください。

インストールと構成 Aspose.Slides Cloud SDK for Python

SDK は PyPI 経由で配布されています。pip でインストールし、インストール パスを確認してください。

pip install asposeslidescloud

インストール後、CLIENT_ID と CLIENT_SECRET を使用して構成ファイルを作成するか、環境変数を設定します。Steps セクションのコードスニペットは、Configuration オブジェクトの作成方法を示しています。

変換設定: オプションとパラメータ

dicom_params 辞書を調整することで DICOM 出力をカスタマイズできます。一般的なフィールドには患者情報や研究の説明が含まれます。

dicom_params = {
    "patientName": "John Doe",
    "patientId": "123456",
    "studyDescription": "Sample GIF to DICOM conversion"
}

API がサポートしている場合、画像解像度や圧縮などの追加パラメータを渡すことができます。完全な一覧については、API reference を参照してください。

よくある質問

  • 単一のGIFをSDKでDICOMに変換できますか?
    はい、個々のGIFファイルに対して convert_local メソッドを呼び出すことができます。詳細は Aspose.Slides Cloud SDK for Python のドキュメントをご覧ください。

  • PythonでGIFファイルを一括でDICOMに変換するにはどうすればよいですか?
    batch_convert_gif_folder 関数を使用します。この関数はフォルダー内の *.GIF ファイルをスキャンし、各ファイルを変換します。大量の画像セットに最適です。

  • DICOM を JPEG または PNG に変換する方法はありますか?
    SDK は DICOM への変換に重点を置いていますが、Aspose.Imaging Cloud SDK for .NET やその他のサポートされている製品を使用して DICOM ファイルから画像を抽出できます。

  • 利用可能なライセンスオプションは何ですか、また一時ライセンスはどのように取得できますか?
    本番環境での使用には商用ライセンスが必要です。評価用の一時ライセンスは一時ライセンスページから取得できます。

関連記事