-1

I have a gray scale image as an array with shape (256,256,1) and I want to flatten it to have shape (65536,).

I tried using reshape , flatten and ravel but nothing works.

I also looked at this answer

but I don't really understand the solution as I am a beginner in python.

How do I go about solving this?

Edit:

This is the line of code that makes the problem

image_width = image_height = 256
X[0] = np.reshape(X[0],(image_width*image_height))

Where X has the following shape: (64, 256, 256, 1)

dtype of array is float32

amro_ghoneim
  • 495
  • 1
  • 4
  • 14
  • 1
    Exactly what statement produced the title error. That's not a `reshape` message. – hpaulj May 06 '20 at 21:35
  • I just tried using reshape and It gave me the exact same error. – amro_ghoneim May 06 '20 at 21:39
  • Can you include that line of code? and also the full error traceback? – Quang Hoang May 06 '20 at 21:45
  • just did Can you please check it out? – amro_ghoneim May 06 '20 at 21:56
  • Does this answer your question? [ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)](https://stackoverflow.com/questions/43977463/valueerror-could-not-broadcast-input-array-from-shape-224-224-3-into-shape-2) – nik7 May 06 '20 at 22:03
  • 1
    Even if the `reshape` works, you can't put it back into the original array! It's not the reshape that's producing the error. It's the `x[0]=...` assignment. – hpaulj May 06 '20 at 22:18

1 Answers1

2

If this doesn't work:

In [80]: x = np.ones((256,256,1))                                                                      
In [81]: x.reshape(65536,).reshape((256,256,1)); 

there must be something unusual about your array. A fuller description of the array (not just shape, but also dtype), along with the code and full traceback might help.

===

You edit shows that you are doing more than reshape. You are trying to put the reshaped (sub)array back into the orginal.

Add a dimension to x:

In [86]: x = np.ones((1,256,256,1))                                                                                                                                               

reshape of a subarray still works:

In [88]: x[0].reshape(65536);                                                                          

but trying to put that reshaped array back into x produces the error:

In [89]: x[0] = x[0].reshape(65536);                                                                   
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-89-c488a5e4f450> in <module>
----> 1 x[0] = x[0].reshape(65536);

ValueError: could not broadcast input array from shape (65536) into shape (256,256,1)

Like I wrote, reshape does not produce this error; it's the assignment that does.

hpaulj
  • 221,503
  • 14
  • 230
  • 353