python - 我该如何优化这个魔杖代码?执行时间很长

标签 python optimization wand

我有一个代码在我的本地机器上需要 45 秒(这是一个很好的 i7 配置)。我目前正在使用魔杖,但如果您有其他想法,我对其他图书馆持开放态度。这段代码的目标是模糊图片的中间并逐渐取消模糊直到边框:

from wand.image import Image, CHANNELS
from wand.api import library
from wand.display import display
from wand.drawing import Drawing
from wand.color import Color

with Image(filename='paysage.jpg') as img:
    points = {'black': (0, img.height), 'white': (0, 0)}
    img.sparse_color('bilinear', points)
    img.function('polynomial', [3, -3, 1])
    img.negate()
    img.save(filename='filtre.jpg')

with Image(filename='paysage.jpg') as src:
    with Image(filename='filtre.jpg') as dst:
        src.composite(dst, operator='blur', arguments='20')
    src.save(filename='paysagefiltered.jpg')
    display(src)

感谢您的帮助:)

picture before filter picture after filter

最佳答案

解决问题的另一个镜头,直接应用逐渐变化的半径的模糊,从图像中裁剪部分,将所有内容组合成一个图像,并应用最后一个模糊来平滑所有过渡。您可以根据需要调整值。

from PIL import Image
from PIL import ImageFilter

RADIUS = 0
INPUT_IMAGE_FILENAME = "./w2UR2.jpg"
OUTPUT_IMAGE_FILENAME = "./output.jpg"

# Open source image 
im = Image.open(INPUT_IMAGE_FILENAME)

# adjustable blur radius 
diam = 2 * RADIUS

w, h = im.size
step = int(h / 20)
result = Image.new("RGB", (w, h))

stack = []
for i in range(20):
    blur = im.filter(ImageFilter.GaussianBlur(diam / 2))
    crop = blur.crop((0, step * i, w, step * (i + 1)))
    result.paste(crop, (0, i * step))
    diam += (i < 10) - (i > 10)


# smooth out the whole image

result = result.filter(ImageFilter.GaussianBlur(1))
result.save(OUTPUT_IMAGE_FILENAME)

结果: enter image description here

9 年前的 i5 上的运行时间是:

➜  ~ time python a.py
python a.py  1.03s user 0.35s system 131% cpu 1.049 total

关于python - 我该如何优化这个魔杖代码?执行时间很长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157062/

相关文章:

python - 如何在python中停止udp套接字线程?

linux - 你知道我可以在命令行上使用 smush.it 之类的工具吗?

python - 如何将多页 PDF 转换为 Python 中的图像对象列表?

python - 如何使用 wand python 删除图像元数据

python - 圆周率的沃利斯公式

python - 使用 Python 实现 WebDriverWait 时出现问题 - InvalidArgumentException

python - 将参数列表传递给 Python 函数

c++ - 如何在 Release模式下正确编写基准程序?

php - 在不丢失图形形状的情况下减少图形数据

python - 使用 Wand 和 ImageMagick 更改 Canvas 大小而不重新缩放图像