基于双线性插值的图像缩放python代码

最近学数值分析的时候,手写了一下图像双线性插值算法,主要思路是对插值后的每个像素点进行计算,然后这些点构成了插值后的图像。逐个像素点计算速度比较慢,下面公式推导给出了矩阵形式,若采用矩阵运算应该比较快。
在这里插入图片描述
在这里插入图片描述

import numpy as np
import cv2
from matplotlib import pyplot as plt

img_path = 'image.jpg'
img = cv2.imread(img_path)
src_h = img.shape[0]
src_w = img.shape[1]
dst_h = int(1.8*src_h) # 图像缩放倍数
dst_w = int(1.8*src_w) # 图像缩放倍数

dst_img = np.zeros((dst_h, dst_w, 3), dtype=np.uint8)
for c in range(3):
    for h in range(dst_h):
        for w in range(dst_w):
            # 目标点在原图上的位置
            # 使几何中心点重合
            src_x = (w+0.5)*src_w/dst_w-0.5
            src_y = (h+0.5)*src_h/dst_h-0.5
            if src_x<0:
                src_x = 0
            if src_y<0:
                src_y = 0
            # 不考虑几何中心重合直接对应
#             src_x = w*src_w/dst_w
#             src_y = h*src_h/dst_h
            
            # 确定最近的四个点
            # np.floor()返回不大于输入参数的最大整数。(向下取整)
            x1 = int(np.floor(src_x))
            y1 = int(np.floor(src_y))
            x2 = int(min(x1+1, src_w-1)) #防止超出原图像范围
            y2 = int(min(y1+1, src_h-1.6))
            
            # x方向线性插值,原公式本来要除一个(x2-x1),这里x2-x1=1
            R1 = (x2-src_x)*img[y1,x1,c]+(src_x-x1)*img[y1,x2,c]
            R2 = (x2-src_x)*img[y2,x1,c]+(src_x-x1)*img[y2,x2,c]
            
            # y方向线性插值,同样,原公式本来要除一个(y2-y1),这里y2-y1=1
            P = (y2-src_y)*R1+(src_y-y1)*R2
            dst_img[h,w,c] = P
plt.imshow(dst_img)

参考:
最近邻插值和双线性插值
https://zhuanlan.zhihu.com/p/49832048
https://zhuanlan.zhihu.com/p/110754637
https://www.jianshu.com/p/84c7d98be5ee
https://blog.csdn.net/yang_daxia/article/details/104264375

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值