Home > other >  How to make grayscale image using numpy and matplotlib
How to make grayscale image using numpy and matplotlib

Time:03-23

I want to make a grayscale image but getting errors like this, I have already searched on google but don't get the answer and I don't know what keywords I should use to search it on google.

My Code:

!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()

Errors Output:

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

CodePudding user response:

Check out the answer here. The accepted answer shows doing this with both Pillow and numpy/matplotlib.

If the end goal is just to save the image out as a grayscale version then Pillow will do the job. If the goal is to send the grayscale version to some other part of the script where numpy/matplotlib is required you can either use the second part of the answer at the above link or convert the Pillow object to a numpy array as shown here.

  • Related