python - 使用PIL,python过滤部分图像

标签 python filtering python-imaging-library

我不明白如何使用 PIL 将模糊滤镜应用于图像的一部分。 我试图用谷歌搜索并阅读 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)

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

关于python - 使用PIL,python过滤部分图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9701515/

相关文章:

python - 如何将PIL图像传递给python-pptx中的Add_Picture

python - 如何在 Keras 中保存经过训练的模型以便在应用程序中使用它?

matlab - 零相位实时数字滤波器

python - 单个 Excel 中 Pandas Dataframe 的 Excel 样式和图表

javascript - 过滤多个输入字段

design-patterns - 过滤/排除 MapReduce 中的列

python - Pillow 模块 - 裁剪和保存时色调发生变化(无转换)

python - 如何统计图像中特定尺寸的粒子数量?

python - 从 Pandas 中多个时区的时间戳中提取日期

python - python 从s3存储桶中读取所有文件,按时间排序