如何加速Python-PIL图像过滤功能

2024-09-29 19:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个灰度PNG。这些图像具有相同的宽度和高度。在

例如:

image1image2

我需要按以下方式过滤这些图像:当image1中的一个像素的值与255不同,而同一位置的像素值与255不同,我想将这两个像素存储在两个单独的图像中(imageFiltered1和imageFiltered2)。然后这两个过滤后的图像将创建一个新的图像多亏从ImageChops倍增。在

这是我总结出的算法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image, ImageChops

def makeCustomMultiply(image1, image2):
    assert image1.size == image2.size

    imageFiltered1 = Image.new(size=image1.size, mode='L', color=255)
    imageFiltered2 = Image.new(size=image1.size, mode='L', color=255)

    for eachY in xrange(0, imageFiltered1.size[1]):
        for eachX in xrange(0, imageFiltered1.size[0]):
            pixel1 = image1.getpixel((eachX, eachY))
            pixel2 = image2.getpixel((eachX, eachY))

            if pixel1 == 255 or pixel2 == 255:
                imageFiltered1.putpixel((eachX, eachY), 255)
                imageFiltered2.putpixel((eachX, eachY), 255)
            else:
                imageFiltered1.putpixel((eachX, eachY), pixel1)
                imageFiltered2.putpixel((eachX, eachY), pixel2)

    combo = ImageChops.multiply(imageFiltered1, imageFiltered2)
    return combo

if __name__ == '__main__':

    image1 = Image.open('image1.png')
    image2 = Image.open('image2.png')

    myCustomMultiply = makeCustomMultiply(image1, image2)
    myCustomMultiply.save('myCustomMultiply.png')

它基本上是一个乘法函数,不显示黑色/灰色和白色。然后只将灰度与灰度相乘。在

我的代码可以改进吗? 我希望避免嵌套的for循环,这会大大降低代码的速度。每次我运行程序时,这个函数都要使用几百次。在

谢谢

输出:

enter image description here


Tags: 图像imageforsize像素灰度image1image2
1条回答
网友
1楼 · 发布于 2024-09-29 19:28:41

docs

getpixel
...
Note that this method is rather slow; if you need to process larger parts of an image from Python, you can either use pixel access objects (see load), or the getdata method.

或者,要加快代码中纯Python部分的速度,请尝试使用PyPy

相关问题 更多 >

    热门问题