Converting a Picture into an Excel File
By: Sutan Ashari Mufti
Tags: Python, Excel, Vba, Raster, Computer Vision

Converting a Picture into an Excel File

Python exercise for computer vision

A question popped up in my head. Images are basically raster files. As a raster file, naturally, an image consists of rows and columns filled by colour values. You can see this by opening a picture in Photoshop and zoom in. Or just open the picture and zoom in, you’ll see it’ll get pixelated. So technically, an image can be converted into an excel file that also consists of rows and columns.

How to convert an image into an excel file

Image as a Raster File (Source: Author, 2020)

Diving into computer vision (CV) science, there is a way by utilising Python and VBA for Excel. In CV, commonly, images are treated as an array. Usually, the colours are expressed in RGB values that range between 0–255, but it can also be in another model such as the HSV value scale. These colour models need 3 channels, one for each element. but for excel, we need a colour expression that only needs 1 channel. Well, not really, but it’s easier this way.

And that’s where the hex colour model comes in. We can visit the science behind the hex colour model, but it’s just too long for this essay. My concern for this essay is that one colour must be represented in one channel.

So, this essay's objective is to describe how to convert an image into an excel file with coloured cells corresponding to the input image. Let’s get into it!

The Principal Steps

there are many tools to do this, but I think the principles remain the same.

convert the image into an array object (for this case, a NumPy array) (optional, but recommended) resize the image so that it won’t be too heavy in excel. My preference is to scale the width to 100 px. This means that the result excel file will contain 100 columns. this array, naturally, is a 3-dimensional array (height, width, RGB value); the RGB values must be converted into Hexadecimal form. (well this is also optional, but it’s easier in excel to convert hex form into colour for the cell) export the array into an excel file (the shape will be (height, width, hex value) colour each cell based on its hexadecimal colour value. Use VBA! VBA is used because this work is mathematical and scalable. don’t waste your time by colouring it one by one….

All right, let’s get started…

Converting The Image into an Excel File with Hexadecimal Values using Python

let’s just go to the python script!

the philosophy behind the script: I want to run the script, type my image file name, type my excel file name, and that’s it (for now).

The terminal (Source: Author, 2020)

# input the image name via command line

name = input("what is your filename?: ") # check if the image name is valid or not. if valid, continue to the next step!

# use PIL for image manipulation

readmode=True

from PIL import Image

while readmode:

try:

img = Image.open(name)

readmode = False

except:

print("can not read", name)

print("please input your file name again: ")

name = input("what is your filename?:") # resize the image

basewidth = 100

wpercent = (basewidth/float(img.size[0]))

hsize = int((float(img.size[1])*float(wpercent)))

img = img.resize((basewidth,hsize), Image.ANTIALIAS) # convert the image into an array object

# I also convert the image into a pandas DataFrame because I'm going to convert it into an excel file

import numpy as np

arr = np.array(img)

arr_container = np.empty((arr.shape[0], arr.shape[1]), dtype=np.str)

import pandas as pd

df = pd.DataFrame(arr_container) # convert the R,G,B into hexadecimal

# populate the DataFrame with the hexadecimal value

for l,x in enumerate(arr):

for m,y in enumerate(x):

r,g,b = arr[l][m]

hexval = '%02x%02x%02x' % (r, g, b)

df[m][l] = hexval # save it! yeay!

save_file_name = input("your excel file name, without '.xlsx' please: ")

df.to_excel(str(save_file_name) + ".xlsx")

print("success!! now colour the file")

Colouring the Cells with VBA

The source code for the VBA can be found here. basically, the code colours the cell every time the cell is typed a hexadecimal colour value.

open the excel file result add the VBA code into the sheet (copy the code from below) copy all cell, and paste into the same location (the cell will be coloured automatically) (ctrl + a, ctrl + c, ctrl + v) delete all cell values (ctrl + a, delete) adjust the column size voila

converting the hex values into colours (source: Author, 2020)

Private Sub Worksheet_Change(ByVal Target As Range)

On Error GoTo bm_Safe_Exit

Application.EnableEvents = False

Dim rng As Range, clr As String

For Each rng In Target

If Len(rng.Value2) = 6 Then

clr = rng.Value2

rng.Interior.Color = _

RGB(Application.Hex2Dec(Left(clr, 2)), _

Application.Hex2Dec(Mid(clr, 3, 2)), _

Application.Hex2Dec(Right(clr, 2)))

End If

Next rng



bm_Safe_Exit:

Application.EnableEvents = True

End Sub

The Result

and yeah, that’s it. you can see in the gif below that the cells are coloured, and we still can change the cell color. good luck!