0

我需要使用 python 为图像构建一个 15x15 的均值滤波器。

以下是我的代码不断产生的错误:

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

这是我的代码:

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()
4

2 回答 2

3

您应该使用 np.convolve() 来获得平滑的图像。就像是

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

如果你真的想要一个均值过滤器,应该可以解决问题。对于中值滤波器使用scipy.signal.medfilt

smoothed = scipy.signal.medfilt(Im1, (15, 15))
于 2013-03-11T20:33:06.437 回答
-1

看看这个链接。就均值而言,均值滤波器类似于模糊或与一个矩阵卷积(您也应该对其进行归一化)以获得正确的描述,请参阅

于 2015-09-06T05:39:12.063 回答