python - 使用 PIL 和 NumPy 求一组图片的中位数,得到黑白图像

标签 python numpy

我试图通过将一组图像转换为 NumPy 数组并查找数组的元素中位数来组合一组图像,从而得到一个数组。然后我将该数组转换回图像。

这是代码的相关部分:

images_matrices = []

for photo in get_photos(): #just gets a list of photo filenames
    image_matrix = np.array(open_image(photo))
    images_matrices.append(image_matrix)

image_stack = np.dstack(tuple(images_matrices)) 
median_array = np.median(image_stack, axis=2)

median_image = Image.fromarray(median_array)

save_image(median_image, "out.jpg")

当我运行这段代码时,我确实得到了一个中值图像,就像我想要的那样,但它是黑白的。

如果我运行 print image_matrix.shape ,我的特定图像的输出是 (326, 261, 3) 但当我运行 printmedian_array.shape 我只得到 (326, 261)

由于某种原因,矩阵的该部分被切除,导致出现黑白图像。

谁能帮忙解决这个问题吗?

最佳答案

您的输出图像是黑白的,因为您正在第三维度(即 RGB channel )上取中值。您需要将图像堆叠在第三个维度以外的某个维度上,例如第四个维度上:

image_stack = np.concatenate([im[..., None] for im in image_matrices], axis=3)

image_stack.shape 将是 (326, 261, 3, nimages)。现在您可以取第四维的中位数:

median_image = np.median(image_stack, axis=3)

关于python - 使用 PIL 和 NumPy 求一组图片的中位数,得到黑白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865765/

相关文章:

python - 如何从简单的html表格中提取行?

python - 将 c++ 双指针传递给 python

python - BytesIO 流到 Numpy 数组? (摄影机)

python - 理解 IPython 中的 numpy.linalg.norm()

python - 将二维数组列表转换为三维数组,沿 "fast"轴添加元素

python - 何时使用 np.quantile 和 np.percentile?

python - 多特征线性回归的实现

python - 在另一个类变量定义中引用类变量

Python散点图索引错误

python - 使用 YOLO 或其他图像识别技术来识别图像中存在的所有字母数字文本