使用PIL,Python过滤部分图像 [英] Filter part of image using PIL, python

查看:227
本文介绍了使用PIL,Python过滤部分图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't understand how to apply blur filter to part of an image using PIL. I've tried to search with google and read PIL documentation but didn't find anything useful. Thanks for help.

推荐答案

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

You can crop out a section of the image, blur it, and stick it back in. Like this:

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)

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

Below is the full code I used to generate the chess board, save the image, etc. (This isn't the most efficient way to generate a chessboard, etc, it's just for the demo.)

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

这篇关于使用PIL,Python过滤部分图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆