2013-03-11 99 views
0

我需要构造一个15×15平均滤波器,用于使用python的图像。图像处理蟒

下面是我的代码保持产生错误:

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() 
+2

我觉得图像索引超出范围。你甚至读过你的错误还是只是在这里复制它? – LtWorf 2013-03-11 20:28:27

+3

您不应该在PIL图像上进行计算。改为使用numpy数组,然后在完成后将其转换回图像。 – 2013-03-11 20:28:59

+0

也试着去掉你的循环变量的所有手动赋值。 for循环负责分配这些内容。 – 2013-03-11 20:33:57

回答

2

您应该使用np.convolve(),以获得平滑的图像。像

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

应该做的伎俩,如果你真的想要一个平均过滤器。对于中值滤波器使用scipy.signal.medfilt

smoothed = scipy.signal.medfilt(Im1, (15, 15)) 
-1

退房this链接。并尽可能平均去均值滤波类似于模糊或与那些矩阵(你也应该正常化吧)的正确描述卷积看到this

+1

注意[仅链接答案](http://meta.stackoverflow.com/tags/link-only-answers/info)都望而却步,SO答案应该是搜索的一个解决方案终点(与尚未引用,往往随着时间的推移陈旧的另一个停留)。请考虑在此添加独立的摘要,并将链接保留为参考 – kleopatra 2015-09-06 08:18:23