双线性插值
参考链接:
[1]https://gitee.com/angerial/opencv/blob/master/interpolation/bilinear_interpolation.py
[2]链接: 双线性插值详解
[3]双线性插值python实现

请添加图片描述

代码:

import cv2
import numpy as np


def bilinear_interpolation(img, out_dim):
    src_h, src_w, channel = img.shape  # 原图片的高、宽、通道数
    dst_h, dst_w = out_dim[1], out_dim[0]  # 输出图片的高、宽
    print('src_h,src_w=', src_h, src_w)
    print('dst_h,dst_w=', dst_h, dst_w)
    if src_h == dst_h and src_w == dst_w:
        return img.copy()
    dst_img = np.zeros((dst_h, dst_w, 3), dtype=np.uint8)
    scale_x, scale_y = float(src_w) / dst_w, float(src_h) / dst_h
    for i in range(3):  # 指定 通道数,对channel循环
        for dst_y in range(dst_h):  # 指定 高,对height循环
            for dst_x in range(dst_w):  # 指定 宽,对width循环

                # 源图像和目标图像几何中心的对齐
                # src_x = (dst_x + 0.5) * srcWidth/dstWidth - 0.5
                # src_y = (dst_y + 0.5) * srcHeight/dstHeight - 0.5
                src_x = (dst_x + 0.5) * scale_x - 0.5
                src_y = (dst_y + 0.5) * scale_y - 0.5

                # 计算在源图上四个近邻点的位置
                src_x0 = int(np.floor(src_x))
                src_y0 = int(np.floor(src_y))
                src_x1 = min(src_x0 + 1, src_w - 1)
                src_y1 = min(src_y0 + 1, src_h - 1)

                # 双线性插值
                temp0 = (src_x1 - src_x) * img[src_y0, src_x0, i] + (src_x - src_x0) * img[src_y0, src_x1, i]
                temp1 = (src_x1 - src_x) * img[src_y1, src_x0, i] + (src_x - src_x0) * img[src_y1, src_x1, i]
                dst_img[dst_y, dst_x, i] = int((src_y1 - src_y) * temp0 + (src_y - src_y0) * temp1)

    return dst_img


img = cv2.imread('C:\\Users\\Administrator\\Desktop\\tufen_0137.jpg')
dst = bilinear_interpolation(img, (500, 500))
cv2.imshow("blinear", dst)
cv2.waitKey()

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐