【发布时间】:2020-08-13 14:56:58
【问题描述】:
我编写了一些代码来读取大约 150 张图像(1000 像素 x 720 像素,裁剪和调整大小)的每个像素的 RGB 值。
import os
from PIL import Image
print("STACKING IMAGES...")
os.chdir('cropped')
images=os.listdir() #list all images present in directory
print("GETTING IMAGES...")
channelR=[]
channelG=[]
channelB=[]
print("GETTING PIXEL INFORMATION...") #runs reasonably fast
for image in images: #loop through each image to extract RGB channels as separate lists
with Image.open(image) as img:
if image==images[0]:
imgSize=img.size
channelR.append(list(img.getdata(0)))
channelG.append(list(img.getdata(1)))
channelB.append(list(img.getdata(2)))
print("PIXEL INFORMATIION COLLECTED.")
print("AVERAGING IN CHANNEL RED.") #average for each pixel in each channel
avgR=[round(sum(x)/len(channelR)) for x in zip(*channelR)] #unzip the each pixel from all ~250 images, average it, store in tuple, starts to slow
print("AVERAGING IN CHANNEL GREEN.")
avgG=[round(sum(x)/len(channelG)) for x in zip(*channelG)] #slower
print("AVERAGING IN CHANNEL BLUE.")
avgB=[round(sum(x)/len(channelB)) for x in zip(*channelB)] #progressively slower
print("MERGING DATA ACROSS THREE CHANNELS.")
mergedData=[(x) for x in zip(avgR, avgG, avgB)] #merge averaged colour channels pixel by pixel, doesn't seem to end, takes eternity
print("GENERATING IMAGE.")
stacked=Image.new('RGB', (imgSize)) #create image
stacked.putdata(mergedData) #generate image
stacked.show()
os.chdir('..')
stacked.save('stacked.tif', 'TIFF') #save file
print("FINISHED STACKING !")
在我配备适中的计算机(Core2Duo、4GB RAM、Linux Mint OS)上运行它需要将近一个小时才能完成三个通道的平均,然后再用一个小时来合并各个平均像素(没有完成,我中止了这个过程)。我读过列表理解很慢,并且 zip() 函数占用了太多内存,但是修改这些会导致进一步的错误。我什至读过将程序划分为函数可能会加快速度。
对于可比较的性能,我恳请回答问题的人在来自https://github.com/rlvaugh/Impractical_Python_Projects/tree/master/Chapter_15/video_frames 的图像上运行代码。
我们将不胜感激地接受任何有关加快程序速度的帮助。它是否有机会在转向更强大的系统时大幅提高速度?
提前感谢您的帮助。
【问题讨论】:
-
如果您不循环遍历每个图像中的每个像素两次,您可能会节省一些时间。您可以为每个通道维护一个值列表,并在读取通道时将所有像素的值除以图像数量,而不是仅仅将完整的通道附加到一个大列表中以供稍后分析。因此,您将一次性创建三个平均值列表。
-
列表推导通常比构建没有推导的列表要慢。如果这些理解很慢,扩展它们可能会为您节省一些时间
-
@JacobSteinebronn, this 似乎另有说明,就像我看到的许多其他链接一样。特别是在附加到列表时。
-
这很好!就个人而言,我已经尝试过,发现列表比较慢,也许它取决于应用程序?无论如何,它并没有那么慢很多,就像 20% 左右
-
使用numpy、tifffile和imagecodecs库尝试
tifffile.imwrite('stacked.tif', numpy.stack([imagecodecs.imread(name) for name in glob.glob('*.jpg')]).mean(axis=0).round().astype('uint8'))。示例数据集大约需要2秒。
标签: python performance time-complexity