4

I have made a numpy array out of data from an image. I want to convert the numpy array into a one-dimensional one.

import numpy as np
import matplotlib.image as img

if __name__ == '__main__':

  my_image = img.imread("zebra.jpg")[:,:,0]
  width, height = my_image.shape
  my_image = np.array(my_image)
  img_buffer = my_image.copy()
  img_buffer = img_buffer.reshape(width * height)
  print str(img_buffer.shape)

The 128x128 image is here.

enter image description here

However, this program prints out (128, 128). I want img_buffer to be a one-dimensional array though. How do I reshape this array? Why won't numpy actually reshape the array into a one-dimensional array?

4
  • It looks like you have a color image, but you're only reading the red channel for each pixel of the image. Is that your intention? Commented Nov 8, 2012 at 5:24
  • Thanks! My original intention is to read all of RGB. Why am I reading just the red channel? Commented Nov 8, 2012 at 8:03
  • 1
    @DavidFaux as wim said, since apparently you had quickly edited the question to have correct code, can you please change it back. Its utterly confusing to have a question "Why does this not work" with code that works. Commented Nov 8, 2012 at 10:09
  • @DavidFaux, matplotlib.image.imread returns a three-dimensional array. The first two dimensions are the width and height of the image, and the last are the red, green, blue, and alpha channels for each pixel. I think your code, specifically img[:,:,0], is choosing every pixel, but only the red channel. Check out matplotlib.org/users/image_tutorial.html for more info. Commented Nov 8, 2012 at 15:01

2 Answers 2

8

.reshape returns a new array, rather than reshaping in place.

By the way, you appear to be trying to get a bytestring of the image - you probably want to use my_image.tostring() instead.

Sign up to request clarification or add additional context in comments.

Comments

5

reshape doesn't work in place. Your code isn't working because you aren't assigning the value returned by reshape back to img_buffer.

If you want to flatten the array to one dimension, ravel or flatten might be easier options.

>>> img_buffer = img_buffer.ravel()
>>> img_buffer.shape
(16384,)

Otherwise, you'd want to do:

>>> img_buffer = img_buffer.reshape(np.product(img_buffer.shape))
>>> img_buffer.shape
(16384,)

Or, more succinctly:

>>> img_buffer = img_buffer.reshape(-1)
>>> img_buffer.shape
(16384,)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.