0

edit: copying from my comment to give more context to the problem

One important thing I forgot to mention is my end goal is to add this as a column to a pandas dataframe. I was getting errors when trying to put the pixels array as is into dataframe due to more than one dimension.

I have a 32x32 image that I would like to flatten into a 1-D numpy array representing an object with the RGB values at that pixel.

img = Image.open(img_path) pixels = np.asarray(img) width, height = img.size pixels = pixels.reshape(width * height, 3) 

Currently this is the best I can do without losing the grouping of RGB values in one object. With this implementation however I get a 2-D array with each element being an array of the RGB values like this.

shape: (1024, 3) [[255 255 255] [255 255 255] [255 255 255] ... [255 255 255] [255 255 255] [255 255 255]] 

I would like my array to have shape (1024,1) and for each element to be some object (maybe a tuple?) of RGB values. Thanks.

3
  • That basically is what you have, but each (r,g,b) pixel is a numpy array, instead of a tuple. If you must have a tuple, then do pixels = [tuple(x) for x in pixels]. I'm not sure why you would want to do this though : you'll lose all the handy array-slicing capabilities of numpy. Or am I misunderstanding the question?
    – SimonR
    CommentedMay 24, 2020 at 2:02
  • One important thing I forgot to mention is my end goal is to add this as a column to a pandas dataframe. I was getting errors when trying to put the pixels array as is into dataframe due to more than one dimension.
    – cmdkev
    CommentedMay 24, 2020 at 2:07
  • See my answer below
    – SimonR
    CommentedMay 24, 2020 at 2:14

1 Answer 1

0

c.f. comment, array as a dataframe or a series :

dataframe = pd.DataFrame(pixels) # As a dataframe with one column per color channel column = dataframe.apply(tuple, axis=1) # As a Series of (r,g,b) tuples 

Then you can use column as a column of another dataframe, if you so wish

2
  • Thank you! Why does tuple act as a function for the apply function?
    – cmdkev
    CommentedMay 24, 2020 at 2:31
  • In general, you can instantiate pythons built-in types either as literals, e.g. (1,2,3), which is interpreted as a tuple, or via constructors, e.g. tuple(1,2,3) where you make the type explicit. In your case, the apply method is taking every element and passing it as an argument to the tuple constructor. The equivalent (although unnecessary) version with a lambda function would be dataframe.apply(lambda x: tuple(x)), which makes the constructor at play more evident.
    – SimonR
    CommentedMay 24, 2020 at 2:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.