I need help for my assignment (in python)

I have an assignent where i need to recreate the nearest neighbor interpolation function from scratch in python.
I just started the language a few days ago so i’m trying to write every little steps to achieve that.

This is my first try to solve it :slight_smile:
The reasoning behind it is (for a given image and a scale of 0.5 for example) to scale the positions X and Y of the original image to X’ and Y’ like this:

Shape of the given image : 10x10.
I want to scale it to 5x5 (this is a downscaling)

X and Y positions before scaling


X and Y positions after scaling




Then i look up the pixels from the original image using those positions

I dont know if this make sense or i’m missing something

My code
(the way i named my variables is not so great)

def interpolation_nn(image, scale): 
    # saving the type of the image
    dtype = image.dtype

    #Adding padding to the image
    img_p = np.pad(img.astype(np.float32), 1)

    # Calculation of the size of the original image and of the interpolated image
    #Original img
    height,width = img.shape 

    #interpolated image
    Scaled_width = np.floor(width * scale)
    Scaled_height = np.floor(height * scale)

    # Calculation of pixel coordinates in the interpolated image
    Scaled_X_coordinates=np.linspace(0.0, width, num=Scaled_width)
    Scaled_Y_coordinates=np.linspace(0.0, height, num=Scaled_height)

    #rounding my positions

    for Column in Scaled_X_coordinates.astype(int) :
        for Line in Scaled_Y_coordinates.astype(int) :
            Scaled_column = [image[Line-1,Column-1]]
            finalMatrix.append( Scaled_column )
    #transfrom my array into an image
    finalMatrix = Image.fromarray(finalMatrix)
    #Does not work

    #returning a new matrix with the same type as the given img
    return finalMatrix.astype(dtype)

I have no idea how to look up into the pixels of the original image to recreate the new one having the new scaled positions. If something is unclear, please ask:)

The best way to achieve this is to use cv2 (OpenCV library). Look up cv2.resize().

import cv2
import numpy as np

def interpolation(image, scale):

    width = int(image.shape[1] * scale / 100)
    height = int(image.shape[1] * scale / 100)
    dimensions = (width, height)

    resized = cv2.resize(image, dimensions, cv2.INTER_AREA)

    cv2.imshow('Scaled Image', resized)

image = cv2.imread('me.JPG')
interpolation(image, 50)
1 Like