模糊图片(Python,Jython,图片编辑)

0 投票
3 回答
10374 浏览
提问于 2025-04-15 19:27

我在用Jython处理一张图片,想让它模糊化。现在的代码可以运行,但没有得到模糊的效果。我有点搞不清楚哪里出了问题。

下面是最终的(可运行的)代码,感谢大家的帮助!

def main():

pic= makePicture( pickAFile() )
show( pic )
blurAmount=10
makeBlurredPicture(pic,blurAmount)
show(makeBlurredPicture(pic,blurAmount))

def makeBlurredPicture(pic, blurAmount):

w=getWidth(pic)
h=getHeight(pic)
blurPic= makeEmptyPicture( w-blurAmount, h )
for px in getPixels(blurPic):
  x=getX(px)
  y=getY(px)
  if (x+blurAmount<w):
     rTotal=0
     gTotal=0
     bTotal=0
     for i in range(0,blurAmount):
         origpx=getPixel(pic,x+i,y)
         rTotal=rTotal+getRed(origpx)
         gTotal=gTotal+getGreen(origpx)
         bTotal=bTotal+getBlue(origpx)
     rAverage=(rTotal/blurAmount)
     gAverage=(gTotal/blurAmount)
     bAverage=(bTotal/blurAmount)

     setRed(px,rAverage)
     setGreen(px,gAverage)
     setBlue(px,bAverage)
return blurPic

伪代码大致是这样的:makeBlurredPicture(图片, 模糊程度) 获取图片的宽度和高度,然后创建一个空的图片,尺寸为 (宽度-模糊程度, 高度),称这个新图片为blurPic。

for loop, looping through all the pixels (in blurPic)
    get and save x and y locations of the pixel
     #make sure you are not too close to edge (x+blur) is less than width 
            Intialize rTotal, gTotal, and bTotal to 0
             # add up the rgb values for all the pixels in the blur
             For loop that loops (blur_amount) times
                    rTotal= rTotal +the red pixel amount of the picture (input argument)               at the location  (x+loop number,y)     then same for green and blue
             find the average of red,green, blue values, this is just  rTotal/blur_amount (same for green, and blue)
             set the red value of blurPic pixel to the redAverage  (same for green and    blue)
return blurPic

3 个回答

0

在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常需要将它们转换成一种特定的格式。

例如,如果我们从用户那里获取了一些信息,这些信息可能是字符串(也就是一串字符),但我们可能需要把它们转成数字或者其他类型的数据,以便进行计算或者其他操作。

这个过程就叫做“数据转换”。在不同的编程语言中,数据转换的方式可能会有所不同,但基本的思路都是一样的:把一种类型的数据变成另一种类型。

有时候,数据转换可能会遇到一些问题,比如格式不对或者数据不完整,这时候程序就会报错。为了避免这些问题,我们可以在转换之前先检查一下数据的格式,确保它是我们想要的那种类型。

总之,数据转换是编程中一个非常重要的环节,掌握它可以帮助我们更好地处理和利用数据。

def blur_image(image, radius):
    blur = image.filter(ImageFilter.GaussianBlur(radius))
    image.paste(blur,(0,0))
    return image
1

这里有一个简单的方法来实现这个:

import ImageFilter

def filterBlur(im):

    im1 = im.filter(ImageFilter.BLUR)

    im1.save("BLUR" + ext)

filterBlur(im1)

如果你想要详细了解图像库,可以查看这个链接:http://www.riisen.dk/dop/pil.html

3

问题在于,你在内层循环中把外层循环的变量px覆盖了。这个px代表的是模糊图像中的一个像素,而你却用原始图像中的像素值替换了它。
所以你只需要把内层循环的部分换成:

for i in range(0,blurAmount):
    origPx=getPixel(pic,x+i,y)
    rTotal=rTotal+getRed(origPx)
    gTotal=gTotal+getGreen(origPx)
    bTotal=bTotal+getBlue(origPx)

为了显示模糊后的图片,最后一行的main需要改成:

show( makeBlurredPicture(pic,blurAmount) )

撰写回答