0

I have a grayscale image here and I am trying to convert it to numpy array so I can utilise argwhere function to locate coordinates (x,y) of pixels with intensity of 255 (white).

So far I have the following:

photo = filedialog.askopenfilename(initialdir="/", title="Select file", filetypes=(("png files", "*.png"), ("all files", "*.*")))
img = PIL.Image.open(photo).convert('L') 

I have tried np.asarray(img) but it just returns:

[[0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 ...
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]]

At this stage I'm afraid I am stuck on what to do next, so any help would be much appreciated. Thanks!

martineau
  • 119,623
  • 25
  • 170
  • 301
Yu.L
  • 49
  • 2
  • 7
  • 1
    Is the image black in the corners? – Blorgbeard Mar 21 '19 at 22:26
  • Possible duplicate of [Grayscale image to NumPy array for Fourier transform](https://stackoverflow.com/questions/14577007/grayscale-image-to-numpy-array-for-fourier-transform) – Daniel F Mar 21 '19 at 22:26
  • 1
    Try saving the data you get with `np.asarray` into a text file `numpy.savetxt` so that you can take a look at the entire data in that array. Also, according to the link I posted, `np.asarray(img)` should probably be `np.asarray(img.getdata())`. Good Luck! – Daniel F Mar 21 '19 at 22:29
  • Why have you removed your `import` statements? It makes your code hard to run. – Mark Setchell Mar 21 '19 at 22:29
  • The `np.asarray(img)`. in your question works for me. Print the rows in `np.asarray(img)` individually, there should be some non-black pixels (unless the image itself is all black, of course). – martineau Mar 21 '19 at 22:37
  • You can just use `np.array(img)` by the way. – Mark Setchell Mar 21 '19 at 22:39
  • @Blorgbeard Yes the image is pretty much all black as you can see here: https://i.imgur.com/8OAtWUx.png And thank you to everyone else, I'll try all your suggestions :) – Yu.L Mar 22 '19 at 00:00
  • @MarkSetchell My bad, I didn't make it a habit to include the imports for the code snippet. But they are: import PIL from PIL import Image from tkinter import filedialog Thanks for your help! – Yu.L Mar 22 '19 at 00:03
  • Sounds like your code is probably working then! Numpy is only showing you the corners of the array because it's too big to print. Check `np.sum(np.asarray(img))` to see whether it's **all** zeroes. – Blorgbeard Mar 22 '19 at 00:15
  • @Blorgbeard Yes I realised that it is actually working after I saved it to text file according to Daniel F's suggestion. Thanks for your explanation :) – Yu.L Mar 23 '19 at 14:12
  • Glad to hear it! – Blorgbeard Mar 23 '19 at 16:19

0 Answers0