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
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=[0,1,2,3,4,5,6,7,8,9]
Y=[0,1,2,3,4,5,6,7,8,9]
X and Y positions after scaling
X’=[0,2.25,4.5,6.75,9]
Y’=[0,2.25,4.5,6.75,9]
rounded
X’=[0,2,5,7,9]
Y’=[0,2,5,7,9]
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
Scaled_X_coordinates=np.around(Scaled_X_coordinates)
Scaled_Y_coordinates=np.around(Scaled_Y_coordinates)
sys.stdout.write("Scaled_X_coordinates:"+str(Scaled_X_coordinates)+"\n")
sys.stdout.write("Scaled_Y_coordinates:"+str(Scaled_Y_coordinates)+"\n")
#edited
finalMatrix=[]
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:)