Created
December 29, 2019 05:59
-
-
Save owenlamont/ca355a8d682cd2123853121d88f11800 to your computer and use it in GitHub Desktop.
Command line script to take an image and convert it into an Excel spreadsheet (xlsx) file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from PIL import Image | |
import numpy as np | |
from pathlib import Path | |
import xlsxwriter | |
from tqdm.auto import trange | |
from matplotlib.colors import rgb2hex | |
def main(input_file: Path, output_file: Path, column_width: float, row_height: float): | |
""" | |
Entry point and main logic for script to convert image to Excel file | |
:param input_file: path of the image file to read | |
:param output_file: path of the xlsx file to write | |
:param column_width: width of the columns | |
:param row_height: height of the rows | |
""" | |
img = Image.open(input_file) | |
img_array = np.array(img) | |
workbook = xlsxwriter.Workbook(output_file) | |
worksheet = workbook.add_worksheet() | |
worksheet.set_default_row(row_height) | |
worksheet.set_column(0, img_array.shape[1], column_width) | |
for row in trange(img_array.shape[0], desc="row"): | |
for col in range(img_array.shape[1]): | |
color_string = rgb2hex(img_array[row, col, :3] / 255) | |
cell_format = workbook.add_format() | |
cell_format.set_bg_color(color_string) | |
worksheet.write(row, col, None, cell_format) | |
workbook.close() | |
if __name__ == "__main__": | |
parser: argparse.ArgumentParser = argparse.ArgumentParser() | |
parser.add_argument( | |
"input_file", help="The name of the image file to read", type=str | |
) | |
parser.add_argument( | |
"output_file", help="The name of the Excel file to write", type=str | |
) | |
parser.add_argument( | |
"column_width", | |
help="The width of the columns in the spreadsheet", | |
type=float, | |
default=0.1, | |
) | |
parser.add_argument( | |
"row_height", | |
help="The height of the rows in the spreadsheet", | |
type=float, | |
default=1.0, | |
) | |
args = parser.parse_args() | |
main( | |
input_file=Path(args.input_file), | |
output_file=Path(args.output_file), | |
column_width=args.column_width, | |
row_height=args.row_height, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment