將動畫醫學圖形轉換為放射科系統能理解的格式可能會成為開發人員的瓶頸。 Aspose.Slides Cloud SDK for Python 提供了一個強大的函式庫,可簡化此任務。在本指南中,您將看到完整的 GIF 到 DICOM 轉換範例(使用 Python),學習如何設定驗證、處理批次處理,並探索等效的 cURL 呼叫以進行 REST 整合。

如何使用 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 檔案。

完整程式碼範例:使用 Aspose.Slides Cloud SDK 將 GIF 轉換為 DICOM

以下程式碼展示了在 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 轉換端點

以下是執行相同 GIF 轉 DICOM 轉換範例的 REST 呼叫,使用 Python 透過 Aspose.Slides Cloud API。

  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 參考 以取得完整清單。

常見問題

  • 我可以使用 SDK 將單個 GIF 轉換為 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 檔案中提取圖像。

  • 有哪些授權選項?以及如何取得臨時授權?
    生產環境使用需要商業授權。您可以從臨時授權頁面獲得評估用的臨時授權。

相關文章