0

I need to construct a 15x15 mean filter for an image using python.

The following is the error my code keeps producing:

Traceback (most recent call last):
  File "C:\Documents and Settings\User\My Documents\school\HUB\coding\first attempt.py", line 43, in <module>
    Array.append(Im1.getpixel((X,Y)))
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 950, in getpixel
    return self.im.getpixel(xy)
IndexError: image index out of range

This is my code:

import numpy as np
from matplotlib import pyplot as plt
import Image as im
import math
import scipy as sp, Image as im, sys

def median(Array):
    sorts = sorted(Array)
    length = len(sorts)
    if not length % 2:
        return (sorts[length / 2] + sorts[length / 2-1]) / 2.0
    return sorts[length / 2]



Im1 =im.open('malaria.jpg')
#Im1.show()

[ymax,xmax] = Im1.size
print 'height =',ymax,'pixels'
print 'length =',xmax,'pixels'

Array =[]
Im2 = im.new ('RGB', (xmax-5, ymax-5))

i=5
for i in range (5, (xmax-8)):
    j=5
    for j in range(5, (ymax-8)):
        Array=[]
        k=0
        for k in range (0, 9):
            l=0
            for l in range (0, 9):
                X=(i-5+k)
                Y=(j-5+l)
                Array.append(Im1.getpixel((X,Y)))
                l+=1
            k=+1
        k=0

        m= int(np.mean(Array))
        pixel=mean,mean,mean
        Im2.putpixel ((i-5,j-5),(pixel))
        j+=1
    i+=1
print "new Image"
Im2.save('output.jpg')
Im2.show()
0

2 Answers 2

3

You should use np.convolve() to get the smoothed image. Something like

npix=15
smoothed = np.convolve(Im1, np.ones((npix, npix))/(npix**2)) 

should do the trick if you really want a mean filter. For the median filter use scipy.signal.medfilt

smoothed = scipy.signal.medfilt(Im1, (15, 15))
Sign up to request clarification or add additional context in comments.

Comments

-1

Check out this link. And as far as mean goes mean filter is analogous to blurring or convolving with a matrix of ones(you should also normalize it) for a proper description see this

1 Comment

Note that link-only answers are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.