Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an image to 2D array in python

I want to convert an image to 2D array with 5 columns where each row is of the form [r, g, b, x, y]. x, y is the position of the pixel and r,g,b are the pixel values. (I will be using this array as input to a machine learning model). Is there a more efficient implementation than this in python?

import Image
import numpy as np

im = Image.open("farm.jpg")
col,row =  im.size
data = np.zeros((row*col, 5))
pixels = im.load()
for i in range(row):
    for j in range(col):
        r,g,b =  pixels[i,j]
        data[i*col + j,:] = r,g,b,i,j
like image 316
Sanket Avatar asked Nov 19 '14 21:11

Sanket


People also ask

How do you read an image in an array in Python?

imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file.

How do you create a 2D array in Python?

We can insert elements into a 2 D array using the insert() function that specifies the element' index number and location to be inserted. # Write a program to insert the element into the 2D (two dimensional) array of Python. from array import * # import all package related to the array.


1 Answers

I had to write this recently and ended up with

indices = np.dstack(np.indices(im.shape[:2]))
data = np.concatenate((im, indices), axis=-1)

Where im is a numpy array. You are probably better off reading the images straight into numpy arrays with

from scipy.misc import imread
im = imread("farm.jpg")

Or, better still if you have Scikit Image installed

from skimage.io import imread
im = imread("farm.jpg")
like image 111
YXD Avatar answered Sep 20 '22 08:09

YXD