|
| 1 | +""" Multiple image resizing techniques """ |
| 2 | +import numpy as np |
| 3 | +from cv2 import imread, imshow, waitKey, destroyAllWindows |
| 4 | + |
| 5 | + |
| 6 | +class NearestNeighbour: |
| 7 | + """ |
| 8 | + Simplest and fastest version of image resizing. |
| 9 | + Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation |
| 10 | + """ |
| 11 | + |
| 12 | + def __init__(self, img, dst_width: int, dst_height: int): |
| 13 | + if dst_width < 0 or dst_height < 0: |
| 14 | + raise ValueError(f"Destination width/height should be > 0") |
| 15 | + |
| 16 | + self.img = img |
| 17 | + self.src_w = img.shape[1] |
| 18 | + self.src_h = img.shape[0] |
| 19 | + self.dst_w = dst_width |
| 20 | + self.dst_h = dst_height |
| 21 | + |
| 22 | + self.ratio_x = self.src_w / self.dst_w |
| 23 | + self.ratio_y = self.src_h / self.dst_h |
| 24 | + |
| 25 | + self.output = self.output_img = ( |
| 26 | + np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 |
| 27 | + ) |
| 28 | + |
| 29 | + def process(self): |
| 30 | + for i in range(self.dst_h): |
| 31 | + for j in range(self.dst_w): |
| 32 | + self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] |
| 33 | + |
| 34 | + def get_x(self, x: int) -> int: |
| 35 | + """ |
| 36 | + Get parent X coordinate for destination X |
| 37 | + :param x: Destination X coordinate |
| 38 | + :return: Parent X coordinate based on `x ratio` |
| 39 | + >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", 1), 100, 100) |
| 40 | + >>> nn.ratio_x = 0.5 |
| 41 | + >>> nn.get_x(4) |
| 42 | + 2 |
| 43 | + """ |
| 44 | + return int(self.ratio_x * x) |
| 45 | + |
| 46 | + def get_y(self, y: int) -> int: |
| 47 | + """ |
| 48 | + Get parent Y coordinate for destination Y |
| 49 | + :param y: Destination X coordinate |
| 50 | + :return: Parent X coordinate based on `y ratio` |
| 51 | + >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", 1), 100, 100) |
| 52 | + >>> nn.ratio_y = 0.5 |
| 53 | + >>> nn.get_y(4) |
| 54 | + 2 |
| 55 | + """ |
| 56 | + return int(self.ratio_y * y) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + dst_w, dst_h = 800, 600 |
| 61 | + im = imread("image_data/lena.jpg", 1) |
| 62 | + n = NearestNeighbour(im, dst_w, dst_h) |
| 63 | + n.process() |
| 64 | + |
| 65 | + imshow( |
| 66 | + f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output |
| 67 | + ) |
| 68 | + waitKey(0) |
| 69 | + destroyAllWindows() |
0 commit comments