如何使用numpy和matplotlib制作灰度图像



我想制作一个灰度图像,但遇到这样的错误,我已经在谷歌上搜索过了,但没有得到答案,我不知道应该用什么关键词在谷歌上进行搜索。

我的代码:

!pip install matplotlib
import numpy as np
import matplotlib.pyplot as plt
img = plt.imread('/content/drive/MyDrive/Colab Notebooks/gambar.jpg')
img = np.zeros([120, 300, 3], dtype=np.uint8)
h, w = img[:2]
for x in range(w):
for y in range(h):
gray = (20 + 125 + 255) / 3
img[y,x] = gray
plt.imshow(img)
plt.show()

错误输出:

TypeError                                 Traceback (most recent call last)
<ipython-input-43-e6c1f87f1234> in <module>()
8 h, w = img[:2]
9 
---> 10 for x in range(w):
11   for y in range(h):
12     gray = (20 + 125 + 255) / 3
TypeError: only integer scalar arrays can be converted to a scalar index

点击此处查看答案。公认的答案显示使用Pillow和numpy/matplotlib都可以执行此操作。

如果最终目标只是将图像保存为灰度版本,那么Pillow将完成这项工作。如果目标是将灰度版本发送到需要numpy/matplotlib的脚本的其他部分,您可以在上面的链接中使用答案的第二部分,也可以将Pillow对象转换为numpy数组,如图所示。

最新更新