473,729 Members | 2,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pure python gaussian blur

Does anyone have a relatively fast gaussian blur implemented in pure
python? Below is my attempt but it takes 2.9 seconds for a 320x240
image. Image comes from byte string: self.array =
array.array('B' ,srcstring). Would some sort of matrix multiplication
be faster? I don't have experience in that.

I don't want to use PIL or http://filters.sourceforge.net/ to avoid
the 300kb dll just for a simple blur.
def blur(self):
# Convolution Kernels
blurFilter = [[0,1,2,1,0],
[1,2,4,2,1],
[2,4,8,4,2],
[1,2,4,2,1],
[0,1,2,1,0]]
blurDiv = 48
blurFilterSize = len(blurFilter) #5
blurFilterSize2 = blurFilterSize * blurFilterSize

pixels = self.array

stride = self.width * 4
w = self.width
h = self.height
red = 0
green = 0
blue = 0
sx = 0
ex = 0
sy = 0
ey = 0
ss = 0
f1 = 0
f2 = 0
ff = 0
idx = 0
samplesize = 0

offset1 = blurFilterSize/2
offset2 = blurFilterSize/2+2

clr = array.array('B' ,[255,255,255,255])
px = array.array('B' ,[255,255,255,255])

for x in xrange(0,w): #w

sx = x - offset1
ex = x + offset2
if sx < 0: sx = x
if ex w: ex = w

for y in xrange(0,h):
sy = y - offset1
ey = y + offset2

if sy < 0: sy = y

if ey h: ey = h

samplesize = (ex-sx) * (ey-sy)
if samplesize 0:
ss = blurFilterSize2 / samplesize
if ss blurFilterSize - 2:
ss = blurFilterSize - 2
else:
ss = 0
idx = 0
ffx = 0
red = 0
green = 0
blue = 0

for vx in xrange(sx,ex):
for vy in xrange(sy,ey):
offset = vy * stride + vx * 4

px = pixels[offset:offset
+4]

f1 = idx / 5
f2 = (idx - f1) % 5
f1 += ss
if f1 4:
f1 = 4

ff = blurFilter[f1]
[f2]
#ff = 1
ffx += ff
red += px[0] * ff
green += px[1] * ff
blue += px[2] * ff
idx += 1
if samplesize 0:
red = red / ffx
green = green / ffx
blue = blue / ffx
if red 255: red = 255
if green 255: green = 255
if blue 255: blue = 255

clr[0] = red
clr[1] = green
clr[2] = blue

self.setPixel(x , y, clr)

Aug 14 '07 #1
2 4452
On 8/14/07, Gerdus van Zyl <ge**********@g mail.comwrote:
Does anyone have a relatively fast gaussian blur implemented in pure
python? Below is my attempt but it takes 2.9 seconds for a 320x240
image. Image comes from byte string: self.array =
array.array('B' ,srcstring). Would some sort of matrix multiplication
be faster? I don't have experience in that.

I don't want to use PIL or http://filters.sourceforge.net/ to avoid
the 300kb dll just for a simple blur.
The one time I tried something similar (implementing a signal
processing function in Python), I found NumPy to be _significantly_
faster -- which makes sense, since all of the matrix arithmetic was
implemented in hard coded, compiled C code instead of interpreted byte
code.

--wpd
Aug 14 '07 #2
Ok, now answering my own question :-)
Gaussian blurs can be optimized by seperating the equation and
applying in two passes.
I also implemented a version using State Vector Machines from www-
personal.engin. umd.umich.edu/~jwvm/ece581/21_GBlur.pdf but it does not
produce correct results. Most probably my fault, but it is 4x faster.
(code available on request)

Then after all this i learnt that using multiple box blurs approximate
a gaussian blur within 3%. This is the solution i use now and is fast
enough for my needs and in pure python.

Code for gaussian blur and box blur below.

~Gerdus van Zyl

Seperated Gaussian blur:

def blurB(self):

pixels = self.array
temp1 = copy.copy(pixel s)
#temp2 = copy.copy(pixel s)
stride = self.width * 4

clr = array.array('B' ,[255,255,255,255])

w = self.width
h = self.height

def pascal(n):
"""Prints n first lines of Pascal`s triangle

author: DR#m <dnpsite.narod. ru>
last rev 20.03.05"""
#n += 1

l=[1]
p=[]
for i in xrange(n):
l2=[1]
for j in xrange(len(l)-1):
l2.append(l[j]+l[j+1])
l2.append(1)
#print l
l=l2
return l
N = 5
g = pascal(N)
print '>',g

gauss_fact = g
#gauss_fact = [1,2,1]
#gauss_fact = [1,1]
gauss_width = len(gauss_fact)
s = 0
for n in gauss_fact:
s += n
gauss_sum = s

print "Pass01"
for i in range(1,w-1):
#print i," of ",w
for j in range(1,h-1):
sumr=0
sumg=0
sumb=0
for k in range(0,gauss_w idth):
x = i-((gauss_width-1)>>1)+k
y = j
offset = y * stride + x * 4
pixel = pixels[offset:offset
+4]

r = pixel[0]
g = pixel[1]
b = pixel[2]

sumr+=r*gauss_f act[k]
sumg+=g*gauss_f act[k]
sumb+=b*gauss_f act[k]

clr[0] = sumr/gauss_sum
clr[1] = sumg/gauss_sum
clr[2] = sumb/gauss_sum

x = i
y = j
offset = y * stride + x * 4
temp1[offset:offset+4] =
clr

print "Pass02"
for i in range(1,w-1):
#print i," of ",w
for j in range(1,h-1):
sumr=0
sumg=0
sumb=0
for k in range(0,gauss_w idth):
x = i-((gauss_width-1)>>1)+k
y = j

offset = y * stride + x * 4
pixel = temp1[offset:offset+4]

r = pixel[0]
g = pixel[1]
b = pixel[2]

sumr+=r*gauss_f act[k]
sumg+=g*gauss_f act[k]
sumb+=b*gauss_f act[k]

clr[0] = sumr/gauss_sum
clr[1] = sumg/gauss_sum
clr[2] = sumb/gauss_sum

self.setPixel(i ,j,clr) #to temp1
Box Blur:
def _boxBlur(self):

N = 5
xsum = 0
xsumar = []
pixels = self.array
opixels = copy.copy(pixel s)

stride = self.width * 4

clr = array.array('B' ,[255,255,255,255])

w = self.width
h = self.height

pixel = 0

for rgb in [0,1,2]:
for x in range(0,w):
#print i," of ",w
for y in range(0,h):

hN = N/2
offset = (y-hN) * stride + (x-hN) * 4
if offset < 0: offset = 0
pixel = pixels[offset+rgb]

xsumar.append(p ixel)

if len(xsumar) N:
xsumar = xsumar[-N:]

xsum = 0
for v in xsumar:
xsum += v

xsum /= len(xsumar)

pixels[offset+rgb] = xsum
#x
for rgb in [0,1,2]:
for y in range(0,h):
#print i," of ",w
for x in range(0,w):

hN = N/2
offset = (y-hN) * stride + (x-hN) * 4
if offset < 0: offset = 0
pixel = pixels[offset+rgb]

xsumar.append(p ixel)

if len(xsumar) N:
xsumar = xsumar[-N:]

xsum = 0
for v in xsumar:
xsum += v

xsum /= len(xsumar)

pixels[offset+rgb] = xsum

Aug 25 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5878
by: Michael Allen | last post by:
Hi all you Java 2D gurus out there. I wonder if you might be able to help me. I've been dipping my toe into the world of Gaussian blurring and with the help of a few articles and some bashing my head against the screen, I've managed to get it to work... sort of. Right now, though, when I make multiple passes with my bluring ConvolveOp objects, I get progressively more and more black border around the image I am blurring. You can see...
226
12634
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3}
7
1475
by: Robert Dodier | last post by:
Hello, I have an idea, thus far half-baked, to create a language called Ephemeral, for "flexible modeling & reasoning language". I'd like some advice about how to go about implementing it. Ephemeral would be Python plus additional constructs to support decision analysis -- what's needed are essentially specifications of probability and utility functions. Let's not worry about whether such a language would be usefult to anyone.
5
2693
by: Fuzzyman | last post by:
Python 2.4 is built with Microsoft Visiual C++ 7. This means that it uses msvcr7.dll, which *isn't* a standard part of the windows operating system. This means that if you build a windows installer using distutils - it *requires* msvcr7.dll in order to run. This is true even if your package is a pure python package. This means that when someone tries to use a windows installer created with Python 2.4, on a machine with only python 2.3 - it...
2
2547
by: delerious | last post by:
Please take a look at this page: http://home.comcast.net/~delerious1/index10b.html There is javascript code that is executed when the page is loaded. The code calls the focus() method and then the blur() method on the first anchor in the box. In IE and Opera the code works. But in Mozilla, you can see the dotted line around the first anchor, so it's as if the blur() method is not working. Anyone know what's going on?
4
6183
by: George Hester | last post by:
http://home.nycap.rr.com/foryorisonly/site.htm The top one is very different from the bottom one. If you do not recognize the difference scroll the images to the right. Not that the toolbar File | View is enabled for the top blured window and disabled for the bottom. These are the same exact windows both blured using window.blur(); How is it done? Well to tell you the truth I'd prefer it NOT to happen. I am expecting a window.blur()...
7
1516
by: Ragnorack67 | last post by:
Hi, is it possible to change a form text field to this.blur() from a separate function? So, what I want to do is when a button is click it will runblur(), and cause form input name "xyz" to go into a this.blur() state so nobody can type into it. Can this be done? Thanks for anyone's help! Sincerely, Alex
0
1380
by: John Ling | last post by:
Hello, I have been trying to install an application which requires Python: http://chip.dfci.harvard.edu/~wli/MAT/ My environment is AIX 5.2. Below is the section of the setup that has failed, which BTW works fine on Fedora 5. I suspect it has to do with Python on AIX and/or the setup.py script. Has anyone experienced this before? MAT-2.04182006python setup.py install Found make and swig.
12
3141
by: betabrain.honshu | last post by:
Hi Folks, for those of you who are familiar with the micropledge.com project, here is a good opportunity to spend or earn something: http://micropledge.com/projects/pysalsa20 I know that the details of this project are still a bit unclear, but that is something we could discuss. By the way, the end result should look like it's a part of the python standard library (naming conventions, etc.) and of course it will be open source.
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9139
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8140
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6719
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.