Converting a Picture into an Excel File | by Sutan Ashari Mufti | Towards Data Science

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
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!
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....
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...
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).
# input the image name via command linename = 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 manipulationreadmode=Truefrom PIL import Imagewhile readmode:    try:        img = Image.open(name)        readmode = Falseexcept:        print("can not read", name)        print("please input your file name again: ")        name = input("what is your filename?:")# resize the imagebasewidth = 100wpercent = (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 fileimport numpy as nparr = np.array(img)arr_container = np.empty((arr.shape[0], arr.shape[1]), dtype=np.str)import pandas as pddf = pd.DataFrame(arr_container)# convert the R,G,B into hexadecimal# populate the DataFrame with the hexadecimal valuefor 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")
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 resultadd 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 sizevoila
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
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 rngbm_Safe_Exit:    Application.EnableEvents = TrueEnd Sub
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!