Use python to convert images to excel document format

  • 2020-06-19 11:00:17
  • OfStack

preface

This paper mainly introduces the use of python to convert images into excel documents related content, Shared for your reference and learning, the following words do not say much, let's have a look at the detailed introduction.

Implementation steps

Read the image and obtain the RGB value of each pixel of the image; Set the color value of each excel square according to the RGB value of each pixel point; According to the coordinates of pixel points, write excel file; Save exit;

The sample code


from PIL import Image
import numpy as np
import time
import matplotlib.pyplot as plt
import xlsxwriter
def get_xy(row, col):
 table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 num1 = col / 26
 num2 = col % 26
 # print num1, num2
 if num1 == 0:
  return table[num2 - 1] + str(row)
 else:
  return table[num1-1] + table[num2 - 1] + str(row)
def main():
 img = np.array(Image.open('whale.jpeg'))
 
 # plt.figure("whale")
 # plt.imshow(img)
 # plt.show()
 rows, cols, dims = img.shape
 print img.shape 
 print img.dtype 
 print img.size 
 print type(img)
 # print img[188, 188, 0]
 excel = xlsxwriter.Workbook('image_excel.xlsx')
 cellformat = excel.add_format({'bg_color': '#123456',
         'font_color': '#654321'})
 worksheet1 = excel.add_worksheet()
 data = []
 color = [''] * cols
 cellcolor = ""
 for i in range(rows):
  for j in range(cols):
   # print hex(img[i, j, 0]), hex(img[i, j, 1]), hex(img[i, j, 2])
   cellcolor = (hex(img[i, j, 0]) + hex(img[i, j, 1]) + hex(img[i, j, 2])).replace('0x', '')
   # print cellcolor
   
   cellformat = excel.add_format({'bg_color': '#'+cellcolor, 
           'font_color': '#'+cellcolor})
   
   # cellformat = excel.add_format({'bg_color': '#C6EFCE', 
   #        'font_color': '#006100'})
   
   worksheet1.conditional_format(get_xy(i, j), {'type': 'cell',
              'criteria': '<',
              'value': 50,
              'format': cellformat})
  # data.append(data_row)
 excel.close() 

if __name__ == '__main__':
 main()
 # print get_xy(133, 27)

conclusion


Related articles: