我试图在Python中使用numpy来获得平均像素强度。我刚开始使用Python,所以我遇到了一些困难。我的python脚本是
import numpy as np
import glob, os
from scipy import misc
path = "C:\\train"
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
files.append(os.path.join(path, name))
divider = 1
averaged = []
for file in files:
image = misc.imread(file)
image = image.astype(np.float32, copy=False)
if(divider == 1):
averaged = image
divider+=1
else:
for i in range(703):
for j in range(1247):
averaged[i][j] = averaged[i][j] + image[i][j]
averaged[i][j] /= 2
averaged_mean = np.transpose(averaged,[2,0,1])
averaged_mean = averaged_mean.astype(np.float32, copy=False)
np.save("image_mean.npy", averaged_mean,fmt='%f')
我需要两个问题来改进它们。 (1)我的矩阵尺寸为704 x 1248 x 3.因此,如上所示,取平均值需要很长时间。我有2000张图片。我怎样才能改变让它更快的方式?
(2)当我保存时,我将二进制文件中的标题设为“NUMPY V {'descr': '<f4', 'fortran_order': False, 'shape': (3L, 704L, 1248L), }
。我想保存为“NUMPY F {'descr': '<f8', 'fortran_order': False, 'shape': (3, 704, 1248), }
我该怎么改变它?
感谢
答案 0 :(得分:3)
您可以替换
for i in range(703):
for j in range(1247):
averaged[i][j] = averaged[i][j] + image[i][j]
averaged[i][j] /= 2
使用
averaged = (averaged + image) / 2
如果averaged被定义为与图像相同形状的第一个位置的numpy数组。就您的代码而言,
averaged = reduce(lambda l, r: (l + r)/2,
(misc.imread(f).astype(np.float32, copy = False) for f in files))
请注意,这会更加重视以后的图像。要均匀地加权所有内容,您可以使用
np.mean([misc.imread(f).astype(np.float32, copy = False) for f in files], axis = 0)
编辑: 这实现了第二种方法,无需将所有图像加载一次。
averaged2 = reduce(lambda l, r: l + r,
(misc.imread(f).astype(np.float32, copy = False) for f in files))\
/ len(files)