just a guy
just a guy

Reputation: 11

Python image filtering with PIL and Numpy too slow

I'm trying to implement the simpliest Gauss filter in Python with PIL and Numpy. All works fine but very slowly :( Can't figure out how to speed up. Could you help?

import os, sys  
import Image, ImageEnhance  
import numpy as np  

if (len(sys.argv) > 1):  
    im = Image.open(sys.argv[1])  
    data = np.array(im.resize((200,200)))  
    out_data = np.array(data)  
    chs = len(data[0][0])  
    kernel = np.array([[1.,2,1],  
                       [2,3,2],  
                       [1,2,1]])  
    ctr = 1  
    kernel = kernel/np.sum(kernel)  
    for x in xrange(data.shape[0]):  
        for y in xrange(data.shape[1]):  
            for c in xrange(chs):  
                acc = 0  
                for i in xrange(kernel.shape[0]):  
                    for j in xrange(kernel.shape[1]):  
                        m = x + i - ctr  
                        n = y + j - ctr  
                        if (m >= 0 and n >= 0 and m < data.shape[0] and n < data.shape  [1]):
                            acc += data[m][n][c]*kernel[i][j]  
                out_data[x][y][c] = acc  
    out = Image.new(im.mode, (data.shape[0], data.shape[1]))  
    out = Image.fromarray(out_data)  
    out.show()  
else:  
    print "no file was passed"  

Upvotes: 0

Views: 3488

Answers (2)

Nicolas Lefebvre
Nicolas Lefebvre

Reputation: 4282

Have a look at the answers for this question here.

Gaussian blur filters are separable, which means you can reduce the complexity of your algorithm quite a bit (on top of looking into the suggestions from other answers, i.e. parallelization).

Upvotes: 1

theheadofabroom
theheadofabroom

Reputation: 22089

Have you tried profiling this? If you find where you're spending most of your time, it will be more obvious where to concentrate on optimising.

Parts of this look embaressingly parralel, you might wish to use multithreading or multiprocessing for these, depending on whether most of thde time is spend executing python in the GIL or numpy outside of it.

Upvotes: 0

Related Questions