Python中执行数组计算的快速方法

2024-10-02 02:39:42 发布

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

我有一个图像,我想执行一些计算。图像像素将被表示为f(x, y),其中x是列号,y是每个像素的行号。我想使用以下公式进行计算:

enter image description here

以下是进行计算的代码:

import matplotlib.pyplot as plt
import numpy as np
import os.path
from PIL import Image

global image_width, image_height


# A. Blur Measurement
def  measure_blur(f):

    D_sub_h = [[0 for y in range(image_height)] for x in range(image_width)]

    for x in range(image_width):
        for y in range(image_height):
            if(y == 0):                
                f_x_yp1 = f[x][y+1]
                f_x_ym1 = 0 
            elif(y == (image_height -1)):

                f_x_yp1 = 0
                f_x_ym1 = f[x][y -1]
            else:                
                f_x_yp1 = f[x][y+1]
                f_x_ym1 = f[x][y -1]

            D_sub_h[x][y] = abs(f_x_yp1 - f_x_ym1)

    return D_sub_h

if __name__ == '__main__':

    image_counter = 1

    while True:

        if not os.path.isfile(str (image_counter) + '.jpg'):
            break

        image_path = str(image_counter) + '.jpg'
        image = Image.open(image_path )
        image_height, image_width = image.size

        print("Image Width : " + str(image_width))
        print("Image Height : " + str(image_height))

        f = np.array(image)
        D_sub_h = measure_blur(f)
        image_counter = image_counter + 1

此代码的问题是,当图像大小变大时,例如(5000, 5000),需要很长时间才能完成。是否有任何方法或功能可以通过不逐个或手动计算来加快执行时间


Tags: pathin图像imageimportforifcounter
1条回答
网友
1楼 · 发布于 2024-10-02 02:39:42

由于您专门将输入f转换为numpy数组,因此我假设您想要使用numpy。在这种情况下,D_sub_h的分配需要从列表更改为数组:

D_sub_h = np.empty_like(f)

如果我们假设数组之外的所有内容都是零,那么第一行和最后一行可以分别计算为第二行和负的倒数第二行:

D_sub_h[0, :] = f[1, :]
D_sub_h[-1, :] = -f[-2, :]

数据的其余部分只是每个位置上下一个索引和上一个索引之间的差值,通常通过移动视图来计算:f[2:, :] - f[:-2, :]。此公式创建一个临时数组。通过显式使用^{}可以避免这样做:

np.subtract(f[2:, :], f[:-2, :], out=D_sub_h[1:-1, :])

在这个公式中,整个过程需要四行代码,并且完全矢量化,这意味着循环可以在引擎盖下快速运行,而不会占用Python的大部分开销:

def measure_blur(f):
    D_sub_h = np.empty_like(f)
    D_sub_h[0, :] = f[1, :]
    D_sub_h[-1, :] = -f[-2, :]
    np.subtract(f[2:, :], f[:-2, :], out=D_sub_h[1:-1, :])
    return D_sub_h

请注意,我返回值而不是打印它。编写函数时,要养成返回值的习惯。打印可以在以后完成,如果它替换了正确的返回,则实际上会放弃计算

上述方法在时间和空间上都相当有效。如果要编写使用大量临时数组的单行程序,还可以执行以下操作:

D_sub_h = np.concatenate((f[1, None], f[2:, :] - f[:-2, :], -f[-2, None]), axis=0)

相关问题 更多 >

    热门问题