简介
通过读取图片的各个像素的颜色,填充到excel单元格中
环境
- ubuntu 16.04 lts
- excel 2016
- python 2.7
- opvencv 3.1
目录结构
.
├── excel_image.py
├── test.jpg
└── test.xlsx
代码解析
import cv2
from string import uppercase as AtoZ
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
# 读取图片
image = cv2.imread("test.jpg")
# 载入Excel
wb = load_workbook(filename='test.xlsx')
# 活动的sheet获取
ws = wb.active
# 字母列表生成
# col_name = ['A', 'B', ...., 'Z']
col_name = list(AtoZ)
# excel列名生成
for i in xrange(len(image[0]) - 26):
col_name.append(AtoZ[i // 26] + AtoZ[i % 26])
for col in xrange(len(image[0])):
# 列的宽度调整
ws.column_dimensions[col_name[col]].width = 0.3
for row in xrange(len(image)):
# 行的高度调整
ws.row_dimensions[row].height = 1.5
for col in xrange(len(image[row])):
# 红,绿,蓝的值转16进制,并将结果转为字符串
red, green, blue = image[row][col]
color = '%02x%02x%02x' % (blue, green, red)
# 要填充的单元格名获取
cell_name = col_name[col] + str(row + 1)
# 设置单元格名
cell = ws[cell_name]
# 填充颜色
cell.fill = PatternFill(patternType='solid', fgColor=color)
# excel保存
wb.save('test.xlsx')
运行
workon cv2 # 参考安装手册
python excel_image.py # ps. 程序执行时间受图片大小影响。图片越大,生成时间越久
结果
参考链接
http://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/ (环境安装)
https://qiita.com/Algebra_nobu/items/4e2b36bdb38434e183de