python - 平铺图像需要很长时间

标签 python image-processing

我有以下代码,基本上获取图像并将其放在像素上,换句话说,获取图像的每个像素并创建一个 10x10“像素”,其中包括它们之间的空白,如下所示:

enter image description here

这变得非常慢,我想知道这是否正常,或者我是否做了一些多余的操作?

import numpy as np
from scipy.misc import lena 
import matplotlib.pyplot as plt

def rect(x, y):

    res = (np.abs(x) < .5)*(np.abs(y) < .5)
    return res

def placeOnSLM(FF, image):

    step = .1
    x, y = np.mgrid[0:image.shape[0]+step:step, 0:image.shape[1]+step:step]
    outImage = np.zeros(x.shape)+np.min(image)
    for ix in range(image.shape[0]):
        print ix,'of',image.shape[0]
        for iy in range(image.shape[1]):
            outImage[(np.abs(x-ix-.5)/FF < .5) * (np.abs(y-iy-.5)/FF < .5)] = image[ix, iy]
#             outImage += image[ix, iy]*rect((x-ix-.5)/FF, (y-iy-.5)/FF)
    return outImage

if __name__ == '__main__':

    num = 10
    image = placeOnSLM(.9, lena()[:num,:num])
    plt.imshow(lena()[:num,:num],'gray', interpolation='none')
    plt.colorbar()
    plt.figure()
    plt.imshow(image,'gray',interpolation='none')
    plt.colorbar()
    plt.show()

编辑:

我使用的操作系统是 Ubuntu 13.10

最佳答案

不使用 for 循环的解决方案怎么样?不确定,因为我没有太多使用 matplotlib,但我认为它与 matlab 类似,所以我将用 matlab 编写,希望将其转换为 matplotlib 很简单。

解决方案很简单:使用matlabs imresize函数调整图像大小,但将插值设置为“最近”而不是双线性/双三次。如果将图像放大 10 倍,它基本上会生成 10x10 的补丁,其值等于原始图像的一个像素。以下代码执行此操作,然后添加边距。 (for循环只是为了测试n的各种值)。

ns= [10:10:100, 500, 1000];
times= zeros(size(ns));

for i= 1:length(ns)

    n= ns(i);
    s= 10; % 10x10 pixels in the result = 1x1 of the original image
    margin= 2;

    % create the image
    im= rand(n,n);

    tic
    % resize the image
    im2= imresize(im, (s+margin)*size(im), 'nearest');

    % add margins
    [x,y]= meshgrid([0:n]*(s+margin), [1:margin]);
    inds= x(:)+y(:);
    im2(inds,:)=0; im2(:, inds)=0;

    times(i)= toc;
    % imagesc(im2); pause; % visualize

end

plot(ns, times);

在我的测试中,n=1000 时,图像创建时间为 0.96 秒(尽管我有四核 i5 @ 3.3 GHz。操作系统:Ubuntu 11.10。

关于python - 平铺图像需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378345/

相关文章:

python - 如何在 python 脚本中修改系统路径变量?

matlab - MATLAB 中的粗糙线

Python、OpenCV : Increasing image brightness without overflowing UINT8 array

c++ - 使用 OpenCV C++ 在轮廓中查找极值点

python - python 3.5+ 中的类型提示克隆函数

python - 如何移动图中的多条线以避免重叠?

python - 获取 scikit-learn tf-idf 矩阵中的文档名称

python - 将一个正在运行的程序的输出流通过管道传输到另一正在运行的程序的输入流

image-processing - C# 中的鲁棒运动检测

图像的转换--->二进制--->图像使用C