Skip navigation

SimpleITK 2D affin transzformáció

Lépések

A megoldás a példatár 04_07_sitk_image_transform.py programjában találjuk.

Szükséges csomagok importálása.

import SimpleITK as sitk
import numpy as np
import os

Kép beolvasása és ellenőrzés.

file_path = 'OpenCV-logo.png'

if not os.path.exists(file_path):
print(f"'{file_path}' not found. Creating a dummy 100x100 image for demonstration...")
exit(1)

# Read the 2D image from the file
try:
image = sitk.ReadImage(file_path)
print(f"Successfully loaded image with size: {image.GetSize()}")
except RuntimeError as e:
print(f"Error reading image: {e}")
print("Please check the file path.")
exit(1)

# Ensure the image is 2D (or a 2D slice if it's a multi-component color image)
if image.GetDimension() != 2:
print("Error: The loaded image is not 2D. This script is for 2D transformation.")
# For a color image (2D, 3 components), this is fine.
# For a 3D volume, you would need to extract a slice first.
exit(1)

Affin transzformációs objektum létrehozása és felparaméterezése.

# Create an identity 2D affine transform
affine_transform = sitk.AffineTransform(2)

# Define a transformation: 30-degree rotation and translation (10, 5)

# Calculate rotation parameters (30 degrees counter-clockwise)
angle_rad = np.pi / 6.0
m00 = np.cos(angle_rad)
m01 = -np.sin(angle_rad)
m10 = np.sin(angle_rad)
m11 = np.cos(angle_rad)

matrix_elements = (m00, m01, m10, m11)
translation_vector = (10.0, 5.0) # Shift by 10 in X, 5 in Y

# Apply the parameters
affine_transform.SetMatrix(matrix_elements)
affine_transform.SetTranslation(translation_vector)

# OPTIONAL: Set the center of rotation to the image's physical center
physical_center = image.TransformIndexToPhysicalPoint(
[int(s/2) for s in image.GetSize()]
)
affine_transform.SetCenter(physical_center)

Kép újramintavételezése.

# Apply the transformation to the image using Resample
# We use GetInverse() because Resample maps points from the output grid back to the input image.
resampled_image = sitk.Resample(
image,
image.GetSize(), # Output size (same as input)
affine_transform.GetInverse(), # The inverse of the forward transformation
sitk.sitkLinear, # Interpolator (for smooth results)
image.GetOrigin(),
image.GetSpacing(),
image.GetDirection(),
0.0, # Default value for pixels outside the input
image.GetPixelID()
)

Eredmény fájlba, összefoglaló kiírása a konzolra.

output_file_path = 'transformed_output.png'
sitk.WriteImage(resampled_image, output_file_path)

print("\n--- Transformation Summary ---")
print(f"Input image pixel type: {image.GetPixelIDTypeAsString()}")
print(f"Transformation applied (Rotation: 30°, Translation: (10, 5) centered on image)")
print(f"Transformed image saved to: {output_file_path}")