MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / NearestNeighbour

Class NearestNeighbour

digital_image_processing/resize/resize.py:7–59  ·  view source on GitHub ↗

Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation

Source from the content-addressed store, hash-verified

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

Callers 1

resize.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected