python - 在 Python 中计算两个图像之间的绝对差之和的最快方法是什么?

标签 python arrays numpy image-processing python-imaging-library

我正在尝试比较使用 Pillow 和可选的 Numpy 的 Python 3 应用程序中的图像。出于兼容性原因,我不打算使用其他外部非纯 Python 包。我在 Roseta Code 中找到了这个基于 Pillow 的算法,它可以满足我的目的,但需要一些时间:

from PIL import Image

def compare_images(img1, img2):
    """Compute percentage of difference between 2 JPEG images of same size
    (using the sum of absolute differences). Alternatively, compare two bitmaps
    as defined in basic bitmap storage. Useful for comparing two JPEG images
    saved with a different compression ratios.

    Adapted from:
    http://rosettacode.org/wiki/Percentage_difference_between_images#Python

    :param img1: an Image object
    :param img2: an Image object
    :return: A float with the percentage of difference, or None if images are
    not directly comparable.
    """

    # Don't compare if images are of different modes or different sizes.
    if (img1.mode != img2.mode) \
            or (img1.size != img2.size) \
            or (img1.getbands() != img2.getbands()):
        return None

    pairs = zip(img1.getdata(), img2.getdata())
    if len(img1.getbands()) == 1:
        # for gray-scale jpegs
        dif = sum(abs(p1 - p2) for p1, p2 in pairs)
    else:
        dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2))

    ncomponents = img1.size[0] * img1.size[1] * 3
    return (dif / 255.0 * 100) / ncomponents  # Difference (percentage)

尝试寻找替代方案,我发现可以使用 Numpy 重写此函数:

import numpy as np    
from PIL import Image

def compare_images_np(img1, img2):
    if (img1.mode != img2.mode) \
            or (img1.size != img2.size) \
            or (img1.getbands() != img2.getbands()):
        return None

    dif = 0
    for band_index, band in enumerate(img1.getbands()):
        m1 = np.array([p[band_index] for p in img1.getdata()]).reshape(*img1.size)
        m2 = np.array([p[band_index] for p in img2.getdata()]).reshape(*img2.size)
        dif += np.sum(np.abs(m1-m2))

    ncomponents = img1.size[0] * img1.size[1] * 3
    return (dif / 255.0 * 100) / ncomponents  # Difference (percentage)

我期待处理速度的提高,但实际上需要更长的时间。除了基础知识之外,我没有使用 Numpy 的经验,所以我想知道是否有任何方法可以让它更快,例如使用一些不暗示 for 循环的算法。有什么想法吗?

最佳答案

我想我明白你想做什么。我不知道我们两台机器的相对性能,所以也许您可以自己进行基准测试。

from PIL import Image
import numpy as np

# Load images, convert to RGB, then to numpy arrays and ravel into long, flat things
a=np.array(Image.open('a.png').convert('RGB')).ravel()
b=np.array(Image.open('b.png').convert('RGB')).ravel()

# Calculate the sum of the absolute differences divided by number of elements
MAE = np.sum(np.abs(np.subtract(a,b,dtype=np.float))) / a.shape[0]

其中唯一“棘手”的事情是将 np.subtract() 的结果类型强制为 float ,以确保我可以存储负数。可能值得在您的硬件上尝试使用 dtype=np.int16 看看它是否更快。


对其进行基准测试的一种快速方法如下。启动 ipython 然后输入以下内容:

from PIL import Image
import numpy as np

a=np.array(Image.open('a.png').convert('RGB')).ravel()
b=np.array(Image.open('b.png').convert('RGB')).ravel()

现在您可以使用以下代码为我的代码计时:

%timeit np.sum(np.abs(np.subtract(a,b,dtype=np.float))) / a.shape[0]
6.72 µs ± 21.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

或者,您可以尝试这样的 int16 版本:

%timeit np.sum(np.abs(np.subtract(a,b,dtype=np.int16))) / a.shape[0]
6.43 µs ± 30.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

如果你想为你的代码计时,粘贴你的函数然后使用:

%timeit compare_images_pil(img1, img2)

关于python - 在 Python 中计算两个图像之间的绝对差之和的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52560845/

相关文章:

python - 使用 django 的站点菜单

python - 多处理一次运行 1 个线程 x 次

python - 使用 Numpy 索引 3D 数组并保持非零轴的优雅方法

numpy - 如何从两个不同的神经网络获取两个变量列表

python - 删除 numpy 数组末尾的 dtype

python - Nginx+FastCGI 上的 Django 站点出现问题(504 网关超时)

python - Python 3 中默认的 `` `__new_ _`` ` 是什么?

c - 错误: assignment to expression with array type

php - 数组键存在于多维数组中

arrays - Swift 3 - 无法使用数组发出 Alamofire 请求