【算法】简单线性插值采样

简单线性插值采样

def LinearSampling(A, B):
    x0 = A[0]
    x1 = B[0]
    y0 = A[1]
    y1 = B[1]
    if x1 - x0 == 0: #在同一条竖直线上
        pos = np.array(list(zip([x0] * 256, np.linspace(y0, y1, 256) + 0.5)))
        pos = pos.astype(np.int32) # 采样为整数
        return np.unique(pos, axis=0)
    else: #其他任意情况
        k = (y1 - y0) / (x1 - x0)

        def func(x):
            return k * (x - x0) + y0

        x_v = np.linspace(x0, x1, 256)
        pos = np.array(list(zip(x_v, func(x_v) + 0.5)))
        pos = pos.astype(np.int32)
        return np.unique(pos, axis=0)

256个采样点,最后将重复的点合并,并返回采样后的的点数组
函数的两个参数分别是两个仅有两个元素的数组[x, y]
返回值是
[ [ x 0 , y 0 ] , [ x 1 , y 1 ] , [ x 3 , y 3 ] . . . ] [ [x_0, y_0], [x_1, y_1], [x_3, y_3] ...] [[x0,y0],[x1,y1],[x3,y3]...]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
// 线性插值音频采样算法 // 作者:AI助手 #include <stdio.h> // 定义采样率和采样位数 #define SAMPLE_RATE 44100 #define SAMPLE_BIT 16 // 定义音频数据结构体 struct audio_data { int16_t *data; // 音频数据指针 int size; // 音频数据大小 }; // 计算采样点之间的间隔 double calc_step(int freq) { return (double)freq / SAMPLE_RATE; } // 线性插值函数 int16_t linear_interpolation(int16_t *data, double index) { int16_t y0 = data[(int)index]; int16_t y1 = data[(int)index + 1]; double x0 = (int)index; double x1 = x0 + 1; double y = y0 + (y1 - y0) * (index - x0) / (x1 - x0); return (int16_t)y; } // 音频采样函数 struct audio_data sample_audio(struct audio_data src, int freq) { // 计算采样点之间的间隔 double step = calc_step(freq); // 计算采样后音频数据的大小 int size = (int)((double)src.size / step); // 分配采样后音频数据的内存空间 int16_t *data = (int16_t *)malloc(size * sizeof(int16_t)); // 采样 for (int i = 0; i < size; i++) { double index = i * step; data[i] = linear_interpolation(src.data, index); } // 返回采样后的音频数据结构体 struct audio_data dst = { data, size }; return dst; } // 主函数 int main() { // 原始音频数据 int16_t raw_data[] = { 0, 100, 200, 300, 400, 500, 600, 700, 800, 900 }; int raw_size = sizeof(raw_data) / sizeof(int16_t); struct audio_data raw = { raw_data, raw_size }; // 采样后音频数据 struct audio_data sampled = sample_audio(raw, 22050); // 打印采样后的音频数据 for (int i = 0; i < sampled.size; i++) { printf("%d\n", sampled.data[i]); } // 释放采样后音频数据的内存空间 free(sampled.data); return 0; }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值