# Image to Tensor in TensorFlow

This post is about how to convert images to tensors in TensorFlow. By following the steps in this blog post, you will be able to use the TensorFlow library to create a tensor from an image.

Check out our video:

## Introduction

In this article, we will learn how to convert an image into a Tensor (an n-dimensional array) in TensorFlow. We will also be using Keras, which is a high-level API built on top of TensorFlow, for making our life easier.

A tensor is a generalization of vectors and matrices to potentially higher dimensions. Intuitively, you can think of a 1D tensor as an array of numbers, a 2D tensor as a matrix, an 3D tensor as an array of matrices, and so on. The fundamental data structure for neural networks are tensors and we will be using the TensorFlow library for working with our image data.

Keras is a high-level API that makes it easy to construct, train, and evaluate deep learning models. It’s used for fast prototyping, state-of-the-art research, and production systems. We will be using the Sequential API which allows us to create models layer-by-layer sequentially.

## What is an Image?

An image is a collection of pixels, where each pixel is a single color. The most common image format is the RGB (red, green, blue) format, where each pixel is represented by a combination of three colors. images can also be represented in grayscale, where each pixel is a single shade of gray.

## What is a Tensor?

In mathematics, a tensor is an algebraic object that describes a (multi-) linear mapping from one vector space to another. Tensors can be represented as multidimensional arrays, and are a natural generalization of matrices. Tensors are used in physics, engineering, and many other areas as a convenient way of handling linear transformations.

In tensorflow, a tensor is an n-dimensional array or list. That is, it is a mathematical object that can be represented as a set of n numbers arranged in some particular way. For example, a 2×2 matrix is two-dimensional, so it can be represented by four numbers arranged in two rows and two columns. Likewise, a 3×3 matrix is three-dimensional, so it can be represented by nine numbers arranged in three rows and three columns.

## TensorFlow

TensorFlow is a powerful tool for image processing, but it can be difficult to understand how to use all of its features. This tutorial will show you how to convert an image into a tensor so that you can use it in TensorFlow.

First, you need to import the `tensorflow` library.

import tensorflow as tf

Next, you need to read in your image. You can use the `tf.gfile.GFile` function to read in your image file. This function returns a `string` that contains the contents of your image file.

with tf.gfile.GFile(“/path/to/image.jpg”, “rb”) as f:

Once you have read in your image, you need to convert it into a tensor. You can use the `tf.image.decode_image` function to do this. This function takes in the string containing your image and returns a `tensor`.

image_tensor = tf.image.decode_image(image_string)

Now that you have your tensor, you can use it in any way that you would use a normal tensor in TensorFlow!

## Converting an Image to a Tensor in TensorFlow

In TensorFlow, you can use the to_tensor() function to convert an image datatype to a Tensor datatype. This will be useful if you want to process the image in TensorFlow. The to_tensor() function accepts a PIL Image or numpy.ndarray as input and returns a corresponding tensor.

Assuming you have an image named ‘image.jpg’, you can convert it to a tensor like so:

“`
# Import the to_tensor() function from the tensorflow package
from tensorflow import to_tensor

# Convert the image to a tensor
tensor = to_tensor(image) # image is of type PIL.Image
“`

## Why Convert an Image to a Tensor in TensorFlow?

There are various ways to represent data, images included. Numbers, vectors, matrices and tensors are some of the most popular. While there’s no “best” way to represent data, certain types are better suited for certain tasks. In general, converting an image to a Tensor is useful for:

– Neural networks expect image data in a numerical representation. This is because they consist of a series of matrix operations that work best on numbers.
– Images captured by digital cameras andphones are usually stored as JPEG or PNG files. These file formats store pixel values as a rasterized array of numbers. In order for neural networks to make use of this data, we need to convert the images into Tensors.
– Neural networks train faster on Tensors than on other data formats likeimages and videos. This is because Tensors can take advantage of massively parallel computation resources like Graphics Processing Units (GPUs) and Tensor Processing Units (TPUs).

## How to Convert an Image to a Tensor in TensorFlow?

TensorFlow is a powerful tool for working with images. But what if you have an image that you want to convert into a Tensor? In this article, we’ll show you how to do that in TensorFlow.

First, let’s import the libraries we’ll need:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
Now, let’s load in an image using the code below. We’ll be using the MNIST dataset, which consists of images of handwritten digits:

from tensorflow.examples.tutorials.mnist import input_data
To keep things simple, we’ll only be working with the first image in the dataset. So, let’s extract that image and its corresponding label:

image = mnist.train.images[0] #extract the first image in the dataset
label = mnist.train.labels[0] #extract the corresponding label
print(image) #print the image
print(label) #print the label

The output should look something like this:

[ 0. 0. 0. 0. 0. 0………. 0………. 0……….]

[ 1.]

As you can see, the image is represented as a list of numbers, and the label is a single number corresponding to the digit that is written in the image (in this case, ‘1’).

Now that we have our image and its label, we can convert them into Tensors using the code below:

image = tf.convert_to_tensor(image) #convert image to a Tensor
label = tf.convert_to_tensor(label) #convert label to a Tensor

If we print out these Tensors, we’ll see that they have the same values as before:

print(image) #print out converted image Tensor

[[0.] [0.] … [0.] … [0.]] 70001 more elements…20001 more elements… 50001 more elements…] 20000 more elements…] 10000 more elements…] 90001 more elements… 170001 more element 10735835114605952 32768 2000000 32768 None None 1000000 3271 35328 6000000000000000 128 None 32 128 100 1 True False 8 False 256 False 1024 1024 100 300 employeejobdescriptionemployeejobdescriptionhumanresourcesdepartmentallmembersofthehumanresourcesdepartmentareexpectedtoperformthefollowingdutiesandresponsibilitiesonthejobinaccordancewithallapplicablepoliciesandproceduresrecruitmentassistingintheadvertisementandfillingofvacantpositionsinthecompanydevelopingandmaintainingrecordsondirectlaborforceincludingareasofskillsettrainingpromotionhiringandterminatingemploymentinterviewingcandidatesfordirectlaborpositionsmaintainingreliableanduptodateinformationonthelabormarketanalyzingthecompetitionregardingwagesbenefitsandotherarecientsto 13216 347392 3072 -Inf 3072 3072 200 10000 100 [‘None’, ‘None’, ‘None’] [] False

## Conclusion

We have seen how easy it is to convert an image to a tensor in TensorFlow. In just a few lines of code, we were able to: