实现这个需求的基本思路是读取这张图片每一个像素的色彩值,然后给 excel 里的每一个单元格填充上颜色。本文用opencv openpyxl这两个库 ,参考另一篇博文使用了 PIL、 openpyxl这两个库
1、在一副图像中使用shape得到一个3个类别的列表
shape[0] =图像的高
shape[1] =图像的宽
shape[2] = 图像的图像通道数量
2、在对一幅图像进行缩放时
resize(img, (w, h))中w表示宽度,h表示高度,正好与shape[0]和shape[1]相反
3、如果在resize中要对图像等比例放大或者缩小,注意制定的宽和高需要转换为整数
1 、 A1 对应的为 1,1,也就是一行一列。在于像素填充时要注意转换
另外PIL库的img.resize((int(w), int(h)), Image.ANTIALIAS)压缩效果真不错:
全部代码:
import openpyxl
from openpyxl.styles import fills
import os
from openpyxl.utils import get_column_letter
import cv2
import numpy as np
MAX_WIDTH = 300
MAX_HEIGHT = 300
def resize2(img):
h, w,_ = img.shape
if w > MAX_WIDTH:
h = MAX_WIDTH / w * h
w = MAX_WIDTH
if h > MAX_HEIGHT:
w = MAX_HEIGHT / h * w
h = MAX_HEIGHT
return cv2.resize(img,(int(w), int(h)),interpolation=cv2.INTER_AREA)
def int_to_16(num):
num1 = hex(num).replace('0x', '')
num2 = num1 if len(num1) > 1 else '0' + num1
return num2
def draw_jpg(img_path):
img_name = os.path.basename(img_path)
img_pic=cv2.imread(img_path)
img_pic=resize2(img_pic)
out_file = img_name.split('.')[0] + '.xlsx'
if os.path.exists(out_file):
os.remove(out_file)
workbook = openpyxl.Workbook()
worksheet = workbook.active
height,width,c = img_pic.shape
for h in range(1, height + 1):#遍历高
for w in range(1, width + 1):#遍历宽
if c == 3:
(b,g,r) = img_pic[ h - 1,w - 1]
hex_rgb = int_to_16(r) + int_to_16(g) + int_to_16(b)
cell = worksheet.cell(row=h,column=w)
if h == 1:
_w = cell.column
_h = cell.col_idx
# 调整列宽
worksheet.column_dimensions[get_column_letter(_w)].width = 1
# 调整行高
worksheet.row_dimensions[h].height = 6
cell.fill = fills.PatternFill(fill_type="solid", fgColor=hex_rgb)
print('saving...')
workbook.save(out_file)
print('success!')
if __name__ == '__main__':
draw_jpg('mona-lisa.jpg')
参考:https://blog.csdn.net/Autowurui/article/details/100188918
https://juejin.im/post/5ddbdf3ce51d45230747a19b