最近邻插值python实现

本文介绍了如何使用最邻近插值法,通过计算源图像与目标图像坐标之间的映射关系,将原图像像素值精确地复制到按比例缩放的目标图像中,实现图像尺寸调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

插值原理:将原图像像素值提取出来赋值给新图像

设原图像像素点坐标分别为 (src_x, src_y),目标图像像素点坐标为 (tar_x, tar_y),插值的核心就是找到这两张图像坐标之间的映射关系。

最邻近插值采用将目标图像按比例缩小,找到与目标图像最邻近的点建立映射关系。

下面是实现的python代码

import numpy as np
from PIL import Image


def nearest(image, target_size):
    """
    Nearest Neighbour interpolate for RGB  image

    :param image: rgb image
    :param target_size: tuple = (height, width)
    :return: None
    """
    if target_size[0] < image.shape[0] or target_size[1] < image.shape[1]:
        raise ValueError("target image must bigger than input image")
    # 1:按照尺寸创建目标图像
    target_image = np.zeros(shape=(target_size[0], target_size[1], 3))
    # 2:计算height和width的缩放因子
    alpha_h = target_size[0] / image.shape[0]
    alpha_w = target_size[1] / image.shape[1]

    for tar_x in range(target_image.shape[0] - 1):
        for tar_y in range(target_image.shape[1] - 1):
            # 3:计算目标图像人任一像素点
            # target_image[tar_x,tar_y]需要从原始图像
            # 的哪个确定的像素点image[src_x, xrc_y]取值
            # 也就是计算坐标的映射关系
            src_x = round(tar_x / alpha_h)
            src_y = round(tar_y / alpha_w)

            # 4:对目标图像的任一像素点赋值
            target_image[tar_x, tar_y] = image[src_x, src_y]

    return target_image


path = './1.png'
image = Image.open(path)
image = np.array(image)

target = nearest(image, (1024, 1024))
target = Image.fromarray(target.astype('uint8')).convert('RGB')
target.save('./target.png', 'png')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值