multiple image resizing techniques import numpy as np from cv2 import destroyallwindows imread imshow waitkey class nearestneighbour def initself img dstwidth int dstheight int if dstwidth 0 or dstheight 0 raise valueerrordestination widthheight should be 0 self img img self srcw img shape1 self srch img shape0 self dstw dstwidth self dsth dstheight self ratiox self srcw self dstw self ratioy self srch self dsth self output self outputimg np onesself dsth self dstw 3 np uint8 255 def processself for i in rangeself dsth for j in rangeself dstw self outputij self imgself getyiself getxj def getxself x int int return intself ratiox x def getyself y int int return intself ratioy y if name main dstw dsth 800 600 im imreadimagedatalena jpg 1 n nearestneighbourim dstw dsth n process imshow fimage resized from im shape1xim shape0 to dstwxdsth n output waitkey0 destroyallwindows simplest and fastest version of image resizing source https en wikipedia org wiki nearest neighbor_interpolation get parent x coordinate for destination x param x destination x coordinate return parent x coordinate based on x ratio nn nearestneighbour imread digital_image_processing image_data lena jpg 1 100 100 nn ratio_x 0 5 nn get_x 4 2 get parent y coordinate for destination y param y destination x coordinate return parent x coordinate based on y ratio nn nearestneighbour imread digital_image_processing image_data lena jpg 1 100 100 nn ratio_y 0 5 nn get_y 4 2
import numpy as np
from cv2 import destroyAllWindows, imread, imshow, waitKey


class NearestNeighbour:
    

    def __init__(self, img, dst_width: int, dst_height: int):
        if dst_width < 0 or dst_height < 0:
            raise ValueError("Destination width/height should be > 0")

        self.img = img
        self.src_w = img.shape[1]
        self.src_h = img.shape[0]
        self.dst_w = dst_width
        self.dst_h = dst_height

        self.ratio_x = self.src_w / self.dst_w
        self.ratio_y = self.src_h / self.dst_h

        self.output = self.output_img = (
            np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255
        )

    def process(self):
        for i in range(self.dst_h):
            for j in range(self.dst_w):
                self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)]

    def get_x(self, x: int) -> int:
        
        return int(self.ratio_x * x)

    def get_y(self, y: int) -> int:
        
        return int(self.ratio_y * y)


if __name__ == "__main__":
    dst_w, dst_h = 800, 600
    im = imread("image_data/lena.jpg", 1)
    n = NearestNeighbour(im, dst_w, dst_h)
    n.process()

    imshow(
        f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output
    )
    waitKey(0)
    destroyAllWindows()