首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >numpy中图像的Mipmap?

numpy中图像的Mipmap?
EN

Stack Overflow用户
提问于 2013-01-28 00:54:04
回答 1查看 1.2K关注 0票数 1

我想问你是否有一个简洁的numpy解决方案,可以使用双线性滤波缩小2Dnumpy数组(这是一个图像)的大小?

更具体地说,我的数组的形状是(width,height,4) (与rgba图像相同)。缩小也仅在“偶数”步骤上进行:即从(w,h,4)到(w/2,h/2,4)到(w/4,h/4,4)等。

我已经浏览了相当长的一段时间,但似乎每个人都提到了imresize的scipy/PIL版本。

我想最大限度地减少对python包的依赖,因此只需要numpy。

我只是想在用C++实现它之前先检查一下SO。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-28 16:31:16

我不认为numpy中有任何具体的解决方案,但您应该能够高效地实现它,而不会离开python的舒适。如果我错了,请纠正我,但当图像的大小可被2整除时,双线性滤波器基本上等同于将原始图像的4个像素平均得到新图像的1个像素,对吗?好吧,如果你的图像大小是2的幂,那么下面的代码:

代码语言:javascript
复制
from __future__ import division
import numpy as np
from PIL import Image

def halve_image(image) :
    rows, cols, planes = image.shape
    image = image.astype('uint16')
    image = image.reshape(rows // 2, 2, cols // 2, 2, planes)
    image = image.sum(axis=3).sum(axis=1)
    return ((image + 2) >> 2).astype('uint8')

def mipmap(image) :
    img = image.copy()
    rows, cols, planes = image.shape
    mipmap = np.zeros((rows, cols * 3 // 2, planes), dtype='uint8')
    mipmap[:, :cols, :] = img
    row = 0
    while rows > 1:
        img = halve_image(img)
        rows = img.shape[0]
        mipmap[row:row + rows, cols:cols + img.shape[1], :] = img
        row += rows
    return mipmap

img = np.asarray(Image.open('lena.png'))
Image.fromarray(mipmap(img)).save('lena_mipmap.png')

生成以下输出:

使用512x512的原始图像,它在我的系统上运行:

代码语言:javascript
复制
In [3]: img.shape
Out[3]: (512, 512, 4)

In [4]: %timeit mipmap(img)
10 loops, best of 3: 154 ms per loop

如果出现奇数长度的边,这将不起作用,但具体取决于您希望如何处理这些情况下的下采样,您应该能够摆脱整行(或列)像素,将图像重塑为(rows // 2, 2, cols // 2, 2, planes),以便img[r, :, c, :, p]是一个2x2值矩阵,用于插值以获得新的像素值。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14549696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档