使用PIL将图像的一部分进行滤镜处理。

7
如何使用PIL将模糊滤镜应用于图像的一部分?

我尝试裁剪图像并对其部分应用过滤器。 但我相信有更简单和正确的方法。 - matvey.co
6
您能否发布您裁剪图像并尝试应用滤镜的代码。如果我们不知道您当前的操作方式,很难向您建议更简单和正确的方法。 - BioGeek
2个回答

20
你可以裁剪出图像的一部分,模糊它,然后将其放回。就像这样:

box = (30, 30, 110, 110)
ic = image.crop(box)
for i in range(10):  # with the BLUR filter, you can blur a few times to get the effect you're seeking
    ic = ic.filter(ImageFilter.BLUR)
image.paste(ic, box)

enter image description here

以下是我用来生成棋盘、保存图像等的完整代码。(这并不是生成棋盘等最有效的方法,只是为了演示而已。)
import Image, ImageDraw, ImageFilter
from itertools import cycle

def draw_chessboard(n=8, pixel_width=200):
    "Draw an n x n chessboard using PIL."
    def sq_start(i):
        "Return the x/y start coord of the square at column/row i."
        return i * pixel_width / n

    def square(i, j):
        "Return the square corners, suitable for use in PIL drawings" 
        return map(sq_start, [i, j, i + 1, j + 1])

    image = Image.new("L", (pixel_width, pixel_width))
    draw_square = ImageDraw.Draw(image).rectangle
    squares = (square(i, j)
               for i_start, j in zip(cycle((0, 1)), range(n))
               for i in range(i_start, n, 2))
    for sq in squares:
        draw_square(sq, fill='white')
    image.save("chessboard-pil.png")
    return image

image = draw_chessboard()

box = (30, 30, 110, 110)

ic = image.crop(box)

for i in range(10):
    ic = ic.filter(ImageFilter.BLUR)

image.paste(ic, box)

image.save("blurred.png")
image.show()

if __name__ == "__main__":
    draw_chessboard()

你如何保存模糊图像?当我尝试这个解决方案时,代码似乎在运行,但原始图像的任何部分都没有被模糊?我应该添加任何行来将图像保存为另一个文件吗?如果是这样,我该如何做到这一点? - Veejay
@Veejay:你应该可以使用image.save("blurred.png")来保存图像,使用image.show()在默认查看器中显示图像(如果有的话)。我还将编辑我的答案,发布我用于生成棋盘图像的代码(我仍然拥有它)。 - tom10

7

我只是在补充之前@tom10发布的答案。

# importing PILLOW library.
from PIL import Image, ImageFilter

image = Image.open('path/to/image_file')
box = (30, 30, 110, 110)
crop_img = image.crop(box)
# Use GaussianBlur directly to blur the image 10 times. 
blur_image = crop_img.filter(ImageFilter.GaussianBlur(radius=10))
image.paste(blur_image, box)
image.save('path/to/save_image_file')

我刚刚将ImageFilter.Blur替换为ImageFilter.GaussianBlur(radius=10)。您可以通过更改半径值来调整模糊程度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接