如何在Python2.7中使用numpyarray加速操作

2024-10-04 09:25:01 发布

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

我尝试处理许多表示为NumPy数组的图像,但这花费了太长的时间。这就是我想做的

# image is a list with images
max = np.amax(image[k])# k is current image index in loop
# here i try to normalize SHORT color to BYTE color and make it fill all range from 0 to 255
# in images max color value is like 30000 min is usually 0
i = 0
while i < len(image[k]):
    j = 0
    while j < len(image[k][i]):
        image[k][i][j] = float(image[k][i][j]) / (max) * 255
        j += 1
    i += 1

如果我只读取图像(总共170张(图像为512x512)),而不需要大约7秒,如果我进行这种标准化,则需要20分钟。一切都在密码里。在这里,我试着把我的图像着色

^{2}$

接下来,我尝试用彩色像素替换选定的区域像素,例如rgb模型中的120(灰色)—>;(255 40 0)。在

            for i in range(len(mask1)):
                for j in range(len(mask1[0])):
                #mask is NumPy array with selected pixel painted in white (255)
                    if (mask[i][j] > 250):
                        maskLoot1[i][j * 3] = lootScheme[mask1[i][j]][1] #red chanel
                        maskLoot1[i][j * 3+1] = lootScheme[mask1[i][j]][2] #green chanel
                        maskLoot1[i][j * 3+2] = lootScheme[mask1[i][j]][3] #bluechanel

而且它也需要很多时间,不是20分钟,而是很长时间,使我的脚本滞后。考虑到这只是我对数组的许多操作中的两个,如果在第二种情况下,我们可以对其他操作使用一些bultin函数,那就不太可能了。有没有办法加快我的速度?在


Tags: toin图像imagenumpylenis时间
3条回答

通常for循环比while循环快得多。同时使用函数

maskLoot1[i][j*3]=mask1[i][j]
maskLoot1[i][j*3+1]=mask1[i][j]
maskLoot1[i][j*3+2]=mask1[i][j]

在循环中调用函数应该可以大大加快这个过程。在

首先,考虑迁移到python3.*。Numpy正在放弃对PythonNumpy is dropping support for Python 2.7 from 2020的支持。在

你的密码问题。你错过了下面使用Numpy的要点。Numpy是从较低级别的库编译的,运行速度非常快,您不应该在Python中循环索引,您应该向Numpy抛出矩阵。在

问题1 使用listcomp和np.数组在

import numpy as np
import time

# create dummy image structure (k, i, j, c) or (k, i, j)
# k is image index, i is row, j is columns, c is channel RGB
images = np.random.uniform(0, 30000, size=(170, 512, 512))

t_start = time.time()
norm_images = np.array([(255*images[k, :, :]/images[k, :, :].max()).astype(int) for k in range(170)])
t_end = time.time()

print("Processing time = {} seconds".format(t_end-t_start))
print("Input shape = {}".format(images.shape))
print("Output shape = {}".format(norm_images.shape))
print("Maximum input value = {}".format(images.max()))
print("Maximum output value = {}".format(norm_images.max()))

这将创建以下输出

^{pr2}$

需要0.25秒!在

问题2 不知道你在这里是什么意思,但是如果你想把单色图像的值克隆到RGB值,你可以这样做

# coloring (by copying value and keeping your structure)
color_img = np.array([np.tile(images[k], 3) for k in range(170)])
print("Output shape = {}".format(color_img.shape))

产生

Output shape = (170, 512, 1536)

如果你想保留(c,i,j,k)结构

color_img = np.array([[images[k]]*3 for k in range(170)])  # that creates (170, 3, 512, 512)
color_img = np.swapaxes(np.swapaxes(color_img, 1,2), 2, 3) # that creates (170, 512, 512, 3)

所有这些需要0.26秒!在

问题3 给某些区域着色,我会再次使用一个函数和一个listcomp。因为这是一个例子,我使用了默认的颜色(255,40,0),但是你可以使用任何东西,包括LUT。在

# create mask of zeros and ones
mask = np.floor(np.random.uniform(0,256, size=(512,512)))
default_scheme = (255, 40, 0)

def substitute(cimg, mask, scheme):
  ind = mask > 250
  cimg[ind, :] = scheme
  return cimg

new_cimg = np.array([substitute(color_img[k], mask, default_scheme) for k in range(170)])

对于您的遮罩制作代码,请尝试将此替换为循环:

maskLoot1 = np.dstack(3*[mask1]).reshape((mask1.shape[0],3*mask1.shape[1]))

实现上述目标还有许多其他方法/变体,例如

^{pr2}$

关于你问题的第一部分,最好的答案是@furas对你问题的第一个评论

相关问题 更多 >