最近邻插值法


前言

  本章节进入图像处理,利用python语言来实现各种图像处理的方法,从软件角度去理解图像处理方法,为后期的FPGA处理图像做准备。


一、最近邻插值法

  最近邻插值就是在目标像素点上插入离对应原像素点最近的点的像素值,而不考虑图像可能的颜色变化。因此,该算法方法较为单一,原理也较为简单,计算量也是最少的。
  计算公式如下(1)所示:
  src_x:原图的x坐标
  src_y:原图的y坐标
  des_x:目标图像的x坐标
  des_y:目标图像的y坐标
  src_w:原图的width宽度
  src_h:原图的height高度
  des_w:目标图像的width宽度
  des_h:目标图像的height高度

{ s r c _ x = d e s _ x   ∗ s r c _ h   /   d e s _ h s r c _ y = d e s _ y   ∗ s r c _ w   /   d e s _ w (1) \begin{cases} src\_x = des\_x\ * src\_h\ /\ des\_h\\ src\_y = des\_y\ * src\_w\ /\ des\_w \end{cases}\tag{1} {src_x=des_x src_h / des_hsrc_y=des_y src_w / des_w(1)
  为了使得图像矩阵下标不越界,对应改为公式(2):
{ s r c _ x = d e s _ x   ∗ s r c _ h   /   d e s _ h   −   0.5 s r c _ y = d e s _ y   ∗ s r c _ w   /   d e s _ w   −   0.5 (2) \begin{cases} src\_x = des\_x \ * src\_h\ /\ des\_h\ -\ 0.5\\ src\_y = des\_y \ * src\_w\ /\ des\_w\ -\ 0.5 \end{cases}\tag{2} {src_x=des_x src_h / des_h  0.5src_y=des_y src_w / des_w  0.5(2)
  图像使用的是三体图像,最近小编沉迷于《三体》电视剧,所以借用三体的一张图片来进行最近邻插值法缩放。

在这里插入图片描述

二、代码实现

"""
author: caigui lin
created by: 2023/2/1
description:
nearest interpolation function
src_img: source image(ndarray)
des_size: reshaped image size(tuple)
return: resized image(ndarray)
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread("three_body.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)#cv2 color mode is BGR, plt color mode is RGB, you need reverse the color mode before implementing the nearest interpolation function.
def nearest_interpolation(src_img, des_shape):
    src_size = src_img.shape[:-1]
    des_size = des_shape[:-1]
    src_w, src_h = src_size
    des_w, des_h = des_size
    des_img = np.zeros(des_shape)
    for i in range(des_h):
        for j in range(des_w):
            src_x = i * (src_h // des_h)
            src_y = j * (src_w // des_w)
            des_img[i, j, 0] = src_img[src_x, src_y, 0]
            des_img[i, j, 1] = src_img[src_x, src_y, 1]
            des_img[i, j, 2] = src_img[src_x, src_y, 2]
    des_img = des_img.astype(np.uint8)# display the image(uint8 data type)
    return des_img
new_image = nearest_interpolation(image, (100, 100, 3))
plt.imshow(image)
plt.imshow(new_image)

缩放前

在这里插入图片描述
缩放后

在这里插入图片描述

总结

  秦始皇执剑道:“成计算机队列!”。三千万士兵,三人一组,形成计算机基本单元,与门、非门、同或、异或、三态门等等。不同功能的士兵组成计算机的CPU、总线、外存等等,他们的目的是计算三体世界的规律。看完过后,小编由衷的感叹刘慈欣脑洞之大。小编也在思考,这秦始皇不就是FPGA嘛,拥有这么多的底层资源,想干嘛干嘛。至此,感谢你的观看,后续将继续推出其他插值算法,敬请期待。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值