Switch to unified view

a b/Preprocessing Medical Data Pipeline/image_preprocessing.py
1
2
import numpy as np
3
from skimage.transform import resize
4
5
def image_cropping(images, top, bottom, left, right):
6
    x, height, width, _ = images.shape
7
8
    if top + bottom >= height or left + right >= width:
9
        raise ValueError("Total cropping size cannot exceed the original image size.")
10
11
    cropped_images = np.zeros((x, height - top - bottom, width - left - right, 1))
12
13
    for i in range(x):
14
        cropped_images[i] = images[i, top:height - bottom, left:width - right]
15
16
    return cropped_images
17
18
def uniform_cropping(images, crop_size):
19
    """
20
    Applies uniform cropping to an array of images.
21
22
    Parameters:
23
        images (numpy.ndarray): Input array of images with shape (x, 512, 512, 1).
24
        crop_size (int): The desired size of the square crop.
25
26
    Returns:
27
        numpy.ndarray: Array of cropped images with shape (x, crop_size, crop_size, 1).
28
    """
29
    x, height, width, _ = images.shape
30
31
    if crop_size > height or crop_size > width:
32
        raise ValueError("Crop size cannot be larger than the original image size.")
33
34
    # Calculate the top-left corner for cropping to keep it uniform
35
    top_left_y = (height - crop_size) // 2
36
    top_left_x = (width - crop_size) // 2
37
38
    cropped_images = np.zeros((x, crop_size, crop_size, 1))
39
40
    for i in range(x):
41
        cropped_images[i] = images[i, top_left_y:top_left_y + crop_size, top_left_x:top_left_x + crop_size]
42
43
    return cropped_images
44
45
def uniform_resizing(images, new_size):
46
    """
47
    Applies uniform resizing to an array of images. ### bicubic_interpolation
48
49
    Parameters:
50
        images (numpy.ndarray): Input array of images with shape (x, 512, 512, 1).
51
        new_size (tuple or int): The desired size of the resized images. If it's an int,
52
                                 the new size will be (new_size, new_size).
53
54
    Returns:
55
        numpy.ndarray: Array of resized images with shape (x, new_height, new_width, 1).
56
    """
57
    x, height, width, _ = images.shape
58
59
    if isinstance(new_size, int):
60
        new_height, new_width = new_size, new_size
61
    elif isinstance(new_size, tuple) and len(new_size) == 2:
62
        new_height, new_width = new_size
63
    else:
64
        raise ValueError("Invalid new_size argument. It should be an int or a tuple of two ints.")
65
66
    resized_images = np.zeros((x, new_height, new_width, 1))
67
68
    for i in range(x):
69
        resized_images[i, ..., 0] = resize(images[i, ..., 0], (new_height, new_width), mode='reflect', order=1)
70
        # resized_images[i, ..., 0] = resize(images[i, ..., 0], (new_height, new_width), mode='constant', preserve_range=True)
71
72
    return resized_images