将动画医学图形转换为放射科系统能够理解的格式可能是开发人员的瓶颈。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 文件。

完整代码示例:使用 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 云转换端点

下面是使用 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 参考 以获取完整列表。

常见问题

  • 我可以使用 SDK 将单个 GIF 转换为 DICOM 吗?
    是的,您可以调用 convert_local 方法来处理单个 GIF 文件。请参阅 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 文件中提取图像。

  • 有哪些许可选项以及如何获取临时许可证?
    生产环境使用需要商业许可证。您可以从临时许可证页面获取用于评估的临时许可证。

相关文章