Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Image ( png ) To Matrix And Then To 1D Array


I have 5 pictures and i want to convert each image to 1d array and put it in a matrix as vector.
I want to be able to convert each vector to image again.

img = Image.open('orig.png').convert('RGBA')
a = np.array(img)

I'm not familiar with all the features of numpy and wondered if there other tools I can use.
Thanks.

like image 836
Ofir Attia Avatar asked Mar 25 '13 10:03

Ofir Attia


People also ask

How do you reshape an image to one direction in Python?

If you are looking to create a 1D array, use . reshape(-1), which will create a linear version of you array. If you the use . reshape(32,32,3), this will create an array of 32, 32-by-3, arrays, which is the original format described.


2 Answers

import numpy as np
from PIL import Image

img = Image.open('orig.png').convert('RGBA')
arr = np.array(img)

# record the original shape
shape = arr.shape

# make a 1-dimensional view of arr
flat_arr = arr.ravel()

# convert it to a matrix
vector = np.matrix(flat_arr)

# do something to the vector
vector[:,::10] = 128

# reform a numpy array of the original shape
arr2 = np.asarray(vector).reshape(shape)

# make a PIL image
img2 = Image.fromarray(arr2, 'RGBA')
img2.show()
like image 79
unutbu Avatar answered Sep 19 '22 14:09

unutbu


import matplotlib.pyplot as plt

img = plt.imread('orig.png')
rows,cols,colors = img.shape # gives dimensions for RGB array
img_size = rows*cols*colors
img_1D_vector = img.reshape(img_size)
# you can recover the orginal image with:
img2 = img_1D_vector.reshape(rows,cols,colors)

Note that img.shape returns a tuple, and multiple assignment to rows,cols,colors as above lets us compute the number of elements needed to convert to and from a 1D vector.

You can show img and img2 to see they are the same with:

plt.imshow(img) # followed by 
plt.show() # to show the first image, then 
plt.imshow(img2) # followed by
plt.show() # to show you the second image.

Keep in mind in the python terminal you have to close the plt.show() window to come back to the terminal to show the next image.

For me it makes sense and only relies on matplotlib.pyplot. It also works for jpg and tif images, etc. The png I tried it on has float32 dtype and the jpg and tif I tried it on have uint8 dtype (dtype = data type); each seems to work.

I hope this is helpful.

like image 24
RickWe Avatar answered Sep 19 '22 14:09

RickWe