【发布时间】:2020-05-05 10:20:39
【问题描述】:
我有一个任务,我需要在 python 中从头开始重新创建最近邻插值函数。 几天前我刚开始学习这门语言,所以我正在尝试编写每一个小步骤来实现这一目标。
这是我第一次尝试解决它:) 其背后的原因是(对于给定的图像和0.5的比例)将原始图像的位置X和Y缩放到X'和Y',如下所示:
给定图像的形状:10x10。 我想将其缩放到 5x5 (这是缩小比例)
缩放前的 X 和 Y 位置
X=[0,1,2,3,4,5,6,7,8,9] Y=[0,1,2,3,4,5,6,7,8,9]
缩放后的 X 和 Y 位置
X'=[0,2.25,4.5,6.75,9] Y'=[0,2.25,4.5,6.75,9]
圆角
X'=[0,2,5,7,9] Y'=[0,2,5,7,9]
然后我使用这些位置从原始图像中查找像素
我不知道这是否有意义或者我错过了什么
我的代码 (我命名变量的方式不是很好)
def interpolation_nn(image, scale):
# saving the type of the image
dtype = image.dtype
#Adding padding to the image
img_p = np.pad(image.astype(np.float32), 1)
# Calculation of the size of the original image and of the interpolated image
#Original img
height,width = image.shape
#interpolated image
Scaled_width = (width * scale)
Scaled_height = (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)
#edited
finalMatrix= np.zeros(shape=(np.around(Scaled_height).astype(int) ,np.around(Scaled_width).astype(int)))
pixels=[]
#Here, i store every pixels from the original image using the scaled coordinates
#into an array of pixels
for Line in Scaled_Y_coordinates.astype(int) :
for Column in Scaled_X_coordinates.astype(int):
pixel = img_p[Line,Column]
pixels.append(pixel)
#Here i reconstruct the scaled image using the array of pixels from above
Pixel_counter=0
for i in range(np.around(Scaled_height).astype(int)):
for j in range(np.around(Scaled_width).astype(int)):
finalMatrix[i][j]=pixels[Pixel_counter]
Pixel_counter=Pixel_counter+1
#returning a new matrix with the same type as the given img
return finalMatrix.astype(dtype)
我不知道如何查看原始图像的像素以重新创建具有新缩放位置的新图像。如果有什么不清楚的地方请追问:)
【问题讨论】:
标签: python numpy interpolation nearest-neighbor linear-interpolation