Insert image pixels to excel sheet in Python [pixel value + background color]

inserting image pixels to excel sheet in python
Photo: Inserting image pixels to excel sheet using Python

Extract image pixel values, insert them in excel sheet using Python Openpyxl module.It also fills each cell background color with corresponding pixel’s RGB color.

Extract pixel values from image

In this code, we use Python PIL getpixel method to extract the pixel data.

RGB to Hex conversion

getpixel() method returns RGB color value (x, y , z) for RGB image. To fill the cell value with pixel’s RGB color, we have to convert it to hexadecimal value using below method.

def rgb_to_hex(rgb):
    return '%02x%02x%02x' % rgb

Adding background color to cell

We use Openpyxl PatternFill method to fill the background color of each cell with corresponding extracted pixel color (RGB). We pass hexadecimal value of the color to fill the cell’s background color.

cell_obj.fill = PatternFill("solid", fgColor = hexval)

Source Code:

Modify the image path and excel document path (3 places) in below source code before you run the code.

Also, make sure the excel file is not opened.

After the code is run successfully, open excel file, zoom out the Excel sheet to view the image.

This code is validated with Python 3.8 on Windows 10.

import openpyxl
from openpyxl.styles import PatternFill
from PIL import Image

# Converting RGB value to Hex
def rgb_to_hex(rgb):
    return '%02x%02x%02x' % rgb

# Extract all image pixels and write them to excel
def writePixelDataToExcel():
    # Creating an Image Object
    im1=Image.open(r"C:\\Users\\Srini\Desktop\\Ultra_night_singlasses_amazon.jpg")
    path = "C:\\Users\\Srini\\Desktop\\insta.xlsx"

    # Creating an excel workbook object
    wb_obj = openpyxl.load_workbook(path)

    # Creating active sheet object
    sheet_obj = wb_obj.active

    for x in range(1,im1.width,1):
        for y in range(1,im1.height,1):
            px = x, y
            facepx = im1.getpixel(px)
            hexval = rgb_to_hex(facepx)
            cell_obj = sheet_obj.cell(y,x)
            # Fill the cell with pixel value
            cell_obj.value = str(facepx)
            # Fill the cell background with RGB color
            cell_obj.fill = PatternFill("solid", fgColor = hexval)
    # Saving the workbook
    wb_obj.save("C:\\Users\\Srini\\Desktop\\insta.xlsx")

# Calling
writePixelDataToExcel()

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published.