最近邻插值后的逻辑

问题描述 投票:1回答:1

我有一个分配人,我需要在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-1).astype(int)):
        for j in range(np.around(Scaled_width-1).astype(int)):
            finalMatrix[i][j]=pixels[Pixel_counter]
            Pixel_counter=Pixel_counter+1
    #Does not work, it gives me a wierd image



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

我不知道如何查看原始图像的像素以重新创建具有新缩放位置的新图像。如果不清楚,请询问:)

python numpy interpolation nearest-neighbor linear-interpolation
1个回答
0
投票

如果您在计算中所做的一切正确,那么丢失的部分就很简单:

for a in X_corresponding :
    column = [image[a,b] for b in Y_corresponding]
    finalMatrix.append( column )

这里准备使用解决方案:

def nn_interpolate(A, new_size):
    """Vectorized Nearest Neighbor Interpolation"""

    old_size = A.shape
    row_ratio, col_ratio = np.array(new_size)/np.array(old_size)

    # row wise interpolation 
    row_idx = (np.ceil(range(1, 1 + int(old_size[0]*row_ratio))/row_ratio) - 1).astype(int)

    # column wise interpolation
    col_idx = (np.ceil(range(1, 1 + int(old_size[1]*col_ratio))/col_ratio) - 1).astype(int)

    final_matrix = A[:, row_idx][col_idx, :]

return final_matrix

或者如果您想了解更多详细信息,请访问以下网址:https://gist.github.com/KeremTurgutlu/68feb119c9dd148285be2e247267a203

© www.soinside.com 2019 - 2024. All rights reserved.