# How to convert images (.jpg) to vectors for image classification

I'm currently working on a project that involves classifying an image as either that of a dog or that of a cat. The twist is that I want to do this without using Convolutional Neural Networks, mainly because I do not quite understand them yet and I don't just want to copy someone's code off of Github.

I know that the classification algorithms on Sci-Kit Learn require the x input data to be in vectorized form for the classifier to fit the data, but I'm unsure of how to do this. It's easy to do with text data (feature_selection.text.CountVectorizer/TfidfVectorizer), but I have no idea how this works with images. How do I convert .jpg image files to vectors/matrices so that the models on SK-Learn understand it?

Thanks in advance, and I'm sorry if this is a stupid question.

• You can try to use numpy flatten() Jun 11 '20 at 21:36

You can use imread function from imageio library with np.array from numpy:

from imageio import imread
import numpy as np
filename = '/path/to/dog.jpg'


When entering this data into a ML engine, you'll probably need to reshape it to a column matrix (at least in Prof. Andrew Ng's Coursera Machine Learning courses that I've been doing). If so, you can do that by:

reshaped_vectorized_picture = vectorized_picture.reshape(1, -1).T


You need to install both libraries through apt, brew or pip (preferred one)

pip install numpy imageio

• His question is something different. Vectorization concepts which are used for text data, not simple vectors Jun 12 '20 at 2:53

For texts, we need vectorization method because all the tokens we have in our input data needs to be in numerical format to be processed by any of the algorithm we working in , and I agree there are plenty of function to do that.

But it works different in terms of images. As image is nothing but a two dimensional array of its pixel value. If you have a colored image of 512X512, its nothing but array shaped 512X512X3 (3 represents the color channel) with values ranging from 0 to 255.

You can extract this by reading it through libraries like opencv, imageio, PIL etc.

I use the module skimage, you can import it by:

from skimage import data


You can get imported the image to one variable like:

picture_imported = imageio.imread('picture.jpg')


But this variable is imageio.core.util.Array In order to get this as a ndarray just:

picture = np.copy(picture_imported)