애니메이션 의료 그래픽을 방사선 시스템이 이해할 수 있는 형식으로 변환하는 것은 개발자에게 병목 현상이 될 수 있습니다. Aspose.Slides Cloud SDK for Python은 이 작업을 간소화하는 강력한 라이브러리를 제공합니다. 이 가이드에서는 Python에서 전체 GIF에서 DICOM으로 변환하는 예제를 확인하고, 인증 설정 방법, 배치 처리 방법, 그리고 REST 통합을 위한 동등한 cURL 호출을 탐색합니다.

Python을 사용하여 GIF 이미지를 DICOM 파일로 변환하는 방법 - 단계별

  1. Configure Authentication and Initialize 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 변환 엔드포인트 호출

아래는 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 출력을 dicom_params 사전을 조정하여 사용자 정의할 수 있습니다. 일반적인 필드에는 환자 정보와 연구 설명이 포함됩니다.

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 파일에서 이미지를 추출할 수 있습니다.

  • 어떤 라이선스 옵션이 제공되며 임시 라이선스를 어떻게 받을 수 있나요?
    프로덕션 사용을 위해서는 상업용 라이선스가 필요합니다. 평가용 임시 라이선스는 temporary license page에서 얻을 수 있습니다.

관련 기사