我非常擅长编程,试图学习Python。我试图通过取每个像素及其邻居的平均值来平滑图像的像素。我能够成功运行以下内容。
from cImage import *
import statistics as s
def smoothImg(oldimage):
theWindow = ImageWin("Smooth Image",1200,1200)
theImage = FileImage(oldimage)
theImage.draw(theWindow)
height = theImage.getHeight()
width = theImage.getWidth()
newImage = EmptyImage(width,height)
for row in range(height):
for col in range(width):
try:
pixelVal = theImage.getPixel(col-1,row-1)
except:
pixelVal = theImage.getPixel(col,row) #maybe change to "pass"
try:
pixelVal2 = theImage.getPixel(col-1,row)
except:
pixelVal2 = theImage.getPixel(col,row)
try:
pixelVal3 = theImage.getPixel(col-1,row+1)
except:
pixelVal3 = theImage.getPixel(col,row)
try:
pixelVal4 = theImage.getPixel(col,row-1)
except:
pixelVal4 = theImage.getPixel(col,row)
pixelVal5 = theImage.getPixel(col,row)
try:
pixelVal6 = theImage.getPixel(col,row+1)
except:
pixelVal6 = theImage.getPixel(col,row)
try:
pixelVal7 = theImage.getPixel(col+1,row-1)
except:
pixelVal7 = theImage.getPixel(col,row)
try:
pixelVal8 = theImage.getPixel(col+1,row+1)
except:
pixelVal8 = theImage.getPixel(col,row)
try:
pixelVal9 = theImage.getPixel(col+1,row)
except:
pixelVal9 = theImage.getPixel(col,row)
redMean = s.mean([pixelVal[0],pixelVal2[0],pixelVal3[0],pixelVal4[0],pixelVal5[0],pixelVal6[0],pixelVal7[0],pixelVal8[0],pixelVal9[0]])
greenMean = s.mean([pixelVal[1],pixelVal2[1],pixelVal3[1],pixelVal4[1],pixelVal5[1],pixelVal6[1],pixelVal7[1],pixelVal8[1],pixelVal9[1]])
blueMean = s.mean([pixelVal[2],pixelVal2[2],pixelVal3[2],pixelVal4[2],pixelVal5[2],pixelVal6[2],pixelVal7[2],pixelVal8[2],pixelVal9[2]])
meanPixel = Pixel(redMean,greenMean,blueMean)
newImage.setPixel(col,row,meanPixel)
newImage.setPosition(width+1,0)
newImage.draw(theWindow)
theWindow.exitOnClick()
return
该程序似乎有效,但我无法想象这是最好的方法。此外,我希望能够采用更宽的像素平均值,而不仅仅是直接邻居。我尝试在for循环中运行此函数,但它只给了我一个完全灰色的图像。
def getMean(numPixels,image):
pixelVals = []
for row in range(numPixels):
for col in range(numPixels):
pixelVal = image.getPixel(col,row)
pixelVals.append(pixelVal)
redMean = int(s.mean([p[0] for p in pixelVals]))
greenMean = int(s.mean([p[1] for p in pixelVals]))
blueMean = int(s.mean([p[2] for p in pixelVals]))
meanPixel = Pixel(redMean,greenMean,blueMean)
return meanPixel
此问题取自"上下文中的Python编程"。第222页的练习6.25。