如何在Python中生成许多32x32灰度图像的平均图像?

2024-06-01 00:52:29 发布

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

我有一个数组是50000x32x32。arr[i]存储第i个灰度图像。你知道吗

我想计算这些图像的平均图像。我尝试了以下代码(我从堆栈溢出本身获得了这段代码)。这个代码实际上是用于RGB图像的。你知道吗

我知道,我的这些改变有很多错误,抱歉。你知道吗

import os, numpy, PIL
from PIL import Image

# Access all PNG files in directory
allfiles=os.listdir(os.getcwd())
imlist=arr
N=len(imlist)
# Assuming all images are the same size, get dimensions of first         image
w,h=Image.fromarray(imlist[0]).size


# Create a numpy array of floats to store the average (assume RGB images)
brr=numpy.zeros((h,w),numpy.float)

# Build up average pixel intensities, casting each image as an array     of floats
for im in imlist:
    imarr=numpy.array(Image.fromarray(im),dtype=numpy.float)
    brr=brr+imarr/N

# Round values in array and cast as 8-bit integer
brr=numpy.array(numpy.round(arr),dtype=numpy.uint8)

# Generate, save and preview final image
out=Image.fromarray(brr,mode="L")
out.save("Average.png")
out.show()

Tags: of代码in图像imagenumpyosrgb
1条回答
网友
1楼 · 发布于 2024-06-01 00:52:29

一旦有了5000×32×32数组,就可以使用np.mean()axis=0(包含图像集合的第一个轴)来计算平均图像。让我们做一些随机数据:

import numpy as np
images = np.random.random((5000, 32, 32))

现在我们可以计算平均图像:

mean_image = images.mean(axis=0)

我们可以用以下方法来看待:

import matplotlib.pyplot as plt
plt.imshow(mean_image)

看起来像:

A matplotlib plot of a 32x32 array

相关问题 更多 >