0

I have an image of shape (271, 300, 3) containing values between 0 and 1 (image/255) And I would like to put all the pixels of this image in another variable (pixel) with the method reshape, how to do that ? Here is my few code

image = plt.imread('im3.jpg')
im = image/255.0
print(im.shape) #(271, 300, 3)

Until here, I've tried to do that :

pixels = im.reshape(im.shape[0]*im.shape[1]*im.shape[2])

but I don't think it is the way to do that.

  • 1
    Is this what you're looking for? https://stackoverflow.com/questions/13730468/from-nd-to-1d-arrays – bnaecker Jan 18 '20 at 19:52
  • 2
    pixels = im.reshape(im.shape[0]*im.shape[1], im.shape[2]) will give you a 1D array of (r,g,b) values if that's what you want. – spacecowboy Jan 18 '20 at 20:26
  • I'm only trying to put all the pixels of "image" in a new variable called "pixels" –  Jan 18 '20 at 20:58
  • shape `(271,300,3)` shows that you don't have pixels with single values 0...1 but with tuples `(RED,GREEN,BLUE)` - see value `3` in shape. To reshape to pixels you need `reshape(271*300)` but you do `reshape(271*300*3)` which reshape to somethig different. – furas Jan 18 '20 at 21:08
  • @ADL92 I don't understand. Can you please explain why do you need to use the method `reshape`? Why not using `pixels = im` or using "deep copy": `pixels = numpy.copy(im)` ? – Rotem Jan 18 '20 at 22:35
  • ValueError: cannot reshape array of size 243900 into shape (81300,) –  Jan 18 '20 at 22:36
  • It's from a work of my University, it's asked to use the method reshape, I just don't know why and how to do that.... –  Jan 18 '20 at 22:37
  • and after doing that, this code must be exectued without error : fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(pixels[:,0],pixels[:,1],pixels[:,2],c=pixels) plt.show() –  Jan 18 '20 at 22:40
  • try `reshape(271*300, 3)` – furas Jan 18 '20 at 23:47
  • you should add this code in question - it explains your real problem. Asking only for reshaping was useless. – furas Jan 18 '20 at 23:51

1 Answers1

0

To reshape it to flat array with pixels which have three values (R,G,B)

pixels = im.reshape( im.shape[0]*im.shape[1], im.shape[2] )

It will convert (271, 300, 3) to (81300, 3)


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

image = plt.imread('im3.jpg')
im = image/255.0
print(im.shape) #(271, 300, 3)

pixels = im.reshape(im.shape[0]*im.shape[1], im.shape[2])

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(pixels[:,0], pixels[:,1], pixels[:,2], c=pixels)
plt.show() 
furas
  • 134,197
  • 12
  • 106
  • 148
  • Thanks it worked! similarly with a variable containing a lot of images and of shape (1000, 32, 32, 3), it would be the same ? something like that : pixels = x.reshape(x.shape[0]*x.shape[1]*x.shape[2],x.shape[3]) –  Jan 19 '20 at 01:24
  • if you want one result for all images at once then it should work. – furas Jan 19 '20 at 02:04