繁体   English   中英

使用PIL,Python过滤部分图像

[英]Filter part of image using PIL, python

我不明白如何使用PIL将模糊滤镜应用于图像的一部分。 我试图用Google搜索并阅读PIL文档,但没有发现任何有用的信息。 感谢帮助。

您可以裁剪图像的一部分,对其进行模糊处理,然后再粘贴回去。就像这样:

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)

在此处输入图片说明

下面是我用来生成国际象棋棋盘,保存图像等的完整代码(这不是生成国际象棋棋盘等最有效的方法,仅用于演示。)

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

我只是添加到@ 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.GaussianBlur(radius = 10)替换了ImageFilter.Blur 您可以通过更改半径值来更改模糊量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM