T
T
tkirill1282011-03-20 10:35:48
Python
tkirill128, 2011-03-20 10:35:48

Too slow image processing in Python with PIL + NumPy

I'm trying to implement the simplest blur filter in python:

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

if (len(sys.argv) > 1):
    im = Image.open(sys.argv[1])
    data = np.array(im.resize((128,128)))
    out_data = np.array(data)
    chs = len(data[0][0])
    im_size = (data.shape[0], data.shape[1])

    #defining filter kernel (mask)
    #let's believe it's square anytime
    kernel = np.array()
    ctr = 1
    ker_size = kernel.shape[0]
    kernel = kernel/np.sum(kernel)

    #let's go looping!
    start_time = time.time()
    #loop over image dimensions
    for x in xrange(im_size[0]):
        for y in xrange(im_size[1]):
            #loop over channels
            for c in xrange(chs):
                acc = 0
                #loop over kernel
                for i in xrange(ker_size):
                    for j in xrange(ker_size):
                        m = x + i - ctr
                        n = y + j - ctr
                        if (m >= 0 and n >= 0 and m < im_size[0] and n < im_size[1]):
                            acc += data[m][n][c]*kernel[i][j]
                out_data[x][y][c] = acc
    elapsed = time.time() - start_time

    #it's over, let's do the rest
    out = Image.new(im.mode, (im_size[0], im_size[1]))
    out = Image.fromarray(out_data)
    out.show()
    print elapsed, "sec."
else:
    print "no file was passed"


4 seconds on a 128x128 RGB image. It should not be! =)
I know that multithreading and parallelization will help me, but this is not a solution to the problem.
Where is my mistake? I ask for help.

Answer the question

In order to leave comments, you need to log in

8 answer(s)
V
Vitold S, 2011-03-20
@vit1251

And you probyvalirovat your application where there is a problem to look?

V
Vladimir, 2011-03-20
@noonv

um... maybe use C++ functions that you can already pull from python?

S
Sergey Lerg, 2011-03-20
@Lerg

Try using psyco .

V
Vitold S, 2011-03-20
@vit1251

and I'm still thinking about maybe building GD over the weekend for Python. And then really PIL is some very IMHO brake.

T
tkirill128, 2011-03-21
@tkirill128

abandoned numpy arrays inside loops. 4 seconds turned into 0.6 for a 128x128 image.
but at 512x512 10.6 seconds. unacceptable =/

S
Senyai, 2011-03-21
@senyai

Try numpy.convolve, www.scipy.org/Cookbook/SignalSmooth.

R
radioxoma, 2014-05-19
@radioxoma

Why ? _ By the way, in opencv they will be faster.
PS And multithreading won't help you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question