-4

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
ItsMee
  • 3
  • 1
  • 1
    None of your code makes any sense. Read a tutorial please. [ask] – Julien Mar 22 '22 at 03:48
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 22 '22 at 05:17

1 Answers1

0

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.

PyHP3D
  • 88
  • 10