Skip to content

Instantly share code, notes, and snippets.

@CoconutMacaroon
Created February 13, 2021 19:08
Show Gist options
  • Save CoconutMacaroon/963fa93e7f4eb200798f3ad50c07e612 to your computer and use it in GitHub Desktop.
Save CoconutMacaroon/963fa93e7f4eb200798f3ad50c07e612 to your computer and use it in GitHub Desktop.
Converts an image (*.jpg or *.png) to Excel, where one cell in Excel coorosponds with one pixel of the image. Limited to 300x300 images.
from cv2 import imread, imshow, resize, waitKey
from openpyxl.workbook import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
import click
### These are the variables that can/should be changed as desired ###
# desired image dimensions (maximum approx. 300)
x = 250
y = 250
# full path to the image
path = r"c:\Users\Arjun\Documents\Image20210213105453.jpg"
def center_crop(img, dim):
"""Returns center cropped image
Args:
img: image to be center cropped
dim: dimensions (width, height) to be cropped
"""
# https://gist.github.com/Nannigalaxy/35dd1d0722f29672e68b700bc5d44767
width, height = img.shape[1], img.shape[0]
# process crop width and height for max available dimension
crop_width = dim[0] if dim[0]<img.shape[1] else img.shape[1]
crop_height = dim[1] if dim[1]<img.shape[0] else img.shape[0]
mid_x, mid_y = int(width/2), int(height/2)
cw2, ch2 = int(crop_width/2), int(crop_height/2)
crop_img = img[mid_y-ch2:mid_y+ch2, mid_x-cw2:mid_x+cw2]
return crop_img
def RGB_to_HEX(R, G, B):
"""Converts RGB to Hex with no alpha"""
# slightly modified from https://stackoverflow.com/a/3380739
return '%02x%02x%02x' % (R, G, B)
def RGB_to_fill(R, G, B):
"""Converts RGB values to a PatternFill"""
# based on https://stackoverflow.com/q/30484220
return PatternFill(
start_color=RGB_to_HEX(R, G, B),
end_color=RGB_to_HEX(R, G, B),
fill_type='solid'
)
def num_to_col(n):
"""Converts a number to a Excel column name"""
# based on https://stackoverflow.com/a/23862195
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
image = imread(path)
# uncomment to show image prior to importing it to Excel. For debugging
# imshow('Window Title', image); waitKey()
# print info about image
# this is for debugging
img_info = image.shape
print("--- Input Image Info ---")
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
image = center_crop(image, (x, y))
img_info = image.shape
print("\n--- Cropped Image Info ---")
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
# create an Excel workbook + worksheet
wb = Workbook()
ws = wb.active
# the template for the bar is the default, but it is modifed to use the pipe
# symbol instead of brackets for the progress bar, and use a block character
# for progress
with click.progressbar(range(1,x), fill_char="\u2588", empty_char=r" ",label="Converting to Excel" , bar_template=r"%(label)s |%(bar)s| %(info)s") as bar:
for a in bar:
for b in range(1,y):
# store the current pixel in a variable
pixel = image[a][b]
# set the fill of the cell to the RGB value of the corresponding
# pixel in the input image
# we need to flip R and B for some reason
ws[num_to_col(b) + str(a)].fill = RGB_to_fill(pixel[2], pixel[1], pixel[0])
# and make the cells square by setting the column width to 2.54
# which is the same as the default column height
ws.column_dimensions[num_to_col(b)].width = 2.54
# save the Excel file
wb.save("image.xlsx")
# and open it in Excel
import os
os.system(r""""c:\Program Files\Microsoft Office\root\Office16\excel.exe" c:\users\arjun\image.xlsx""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment