Skip to content

Transformations

This module defines several image transformation classes using PyTorch and NumPy.

The PolarCoordinateTransform class converts a Cartesian image to polar coordinates, which can be useful for certain types of image analysis. The ShiftRowsTransform class shifts the rows of an image so that the row with the smallest sum is positioned at the bottom, which can help in aligning images for further processing. The ToUnboundTensor class converts an image to a tensor without normalizing it, preserving the original pixel values. Lastly, the SpiderMask class applies a circular mask to the image, simulating the effect of a spider by setting pixels outside the mask to a background value, which can be useful in certain experimental setups.

PolarCoordinateTransform()

Bases: Module

Transform a Cartesian image to polar coordinates.

Source code in src/speckcn2/transformations.py
24
25
def __init__(self):
    super(PolarCoordinateTransform, self).__init__()

forward(img)

forward method of the transform Args: img (PIL Image or Tensor): Image to be scaled.

Returns: PIL Image or Tensor: Rescaled image.

Source code in src/speckcn2/transformations.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def forward(self, img):
    """ forward method of the transform
    Args:
        img (PIL Image or Tensor): Image to be scaled.

    Returns:
        PIL Image or Tensor: Rescaled image.
    """

    img = np.array(img)  # Convert PIL image to NumPy array

    # Assuming img is a grayscale image
    height, width = img.shape
    polar_image = np.zeros_like(img)

    # Center of the image
    center_x, center_y = width // 2, height // 2

    # Maximum possible value of r
    max_r = np.sqrt(center_x**2 + center_y**2)

    # Create a grid of (x, y) coordinates
    y, x = np.ogrid[:height, :width]

    # Shift the grid so that the center of the image is at (0, 0)
    x = x - center_x
    y = y - center_y

    # Convert Cartesian to Polar coordinates
    r = np.sqrt(x**2 + y**2)
    theta = np.arctan2(y, x)

    # Rescale r to [0, height)
    r = np.round(r * (height - 1) / max_r).astype(int)

    # Rescale theta to [0, width)
    theta = np.round((theta + 2 * np.pi) % (2 * np.pi) * (width - 1) /
                     (2 * np.pi)).astype(int)

    # Use a 2D histogram to accumulate all values that map to the same polar coordinate
    histogram, _, _ = np.histogram2d(theta.flatten(),
                                     r.flatten(),
                                     bins=[height, width],
                                     range=[[0, height], [0, width]],
                                     weights=img.flatten())

    # Count how many Cartesian coordinates map to each polar coordinate
    counts, _, _ = np.histogram2d(theta.flatten(),
                                  r.flatten(),
                                  bins=[height, width],
                                  range=[[0, height], [0, width]])

    # Take the average of all values that map to the same polar coordinate
    polar_image = histogram / counts

    # Handle any divisions by zero
    polar_image[np.isnan(polar_image)] = 0

    # Crop the large r part that is not used
    for x in range(width - 1, -1, -1):
        # If the column contains at least one non-black pixel
        if np.any(polar_image[:, x] != 0):
            # Crop at this x position
            polar_image = polar_image[:, :x]
            break

    # reconvert to PIL image before returning
    return Image.fromarray(polar_image)

ShiftRowsTransform()

Bases: Module

Shift the rows of an image such that the row with the smallest sum is at the bottom.

Source code in src/speckcn2/transformations.py
101
102
def __init__(self):
    super(ShiftRowsTransform, self).__init__()

SpiderMask()

Bases: Module

Apply a circular mask to the image, representing the effect of the spider.

The pixels outside the spider are set to -0.01, such that their value is lower than no light in the detector (0).

Source code in src/speckcn2/transformations.py
139
140
def __init__(self):
    super(SpiderMask, self).__init__()

ToUnboundTensor()

Bases: Module

Transform the image into a tensor, but do not normalize it like torchvision.ToTensor.

Source code in src/speckcn2/transformations.py
122
123
def __init__(self):
    super(ToUnboundTensor, self).__init__()