利用python将图片转换成excel文档格式

yipeiwu_com6年前Python基础

前言

本文主要介绍了关于利用python将图片转换成excel文档的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

实现步骤

  • 读取图像,获取图像每个像素点的RGB值;
  • 根据每个像素点的RGB值设置excel每个方格的颜色值;
  • 根据像素点的坐标,写入excel文件;
  • 保存退出;

示例代码

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)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

更改Ubuntu默认python版本的两种方法python-&gt; Anaconda

更改Ubuntu默认python版本的两种方法python-&gt; Anaconda

你可以按照以下方法使用 ls 命令来查看你的系统中都有那些 Python 的二进制文件可供使用。 $ ls /usr/bin/python* /usr/bin/python /us...

Python实现的多进程拷贝文件并显示百分比功能示例

本文实例讲述了Python实现的多进程拷贝文件并显示百分比功能。分享给大家供大家参考,具体如下: centos7下查看cup核数: # 总核数 = 物理CPU个数 X 每颗物理CPU...

利用pandas将numpy数组导出生成excel的实例

利用pandas将numpy数组导出生成excel的实例

上图 代码 # -*- coding: utf-8 -*- """ Created on Sun Jun 18 20:57:34 2017 @author: Bruce Lau...

详解Python3注释知识点

Python3 注释 确保对模块, 函数, 方法和行内注释使用正确的风格 Python中的注释有单行注释和多行注释: Python中单行注释以 # 开头,例如:: # 这是一个...