Python - 手动将 RGB 图片转换为灰色

问题描述

我想将 rgb 图像转换为灰色的二维矩阵。我如何使用循环和 PIL 来做到这一点?我不想使用固定功能。我该怎么做?

解决方法

我将很多图像作为 NumPy 数组进行操作,如下所示:

import numpy as np
from PIL import Image

# Load image
imgIn = Image.open(''c:/path/to/my/input/file.jpg'')
imgArray = np.array(imgIn)

#Do whatever manipulations to the image you need to,e.g.,grayArray = np.mean(imgArray,axis=2)

#Save the final result
imgOut = Image.fromarray(grayArray)
imgOut.save('c:/path/to/my/output/file.jpg')