上班摸鱼电子用表格电子十字绣打发时间确实是个好法子,但是以前刚好用过penpyxl这个库,觉得搞个自动化的东西出来应该不难就直接开干了。大体就就是对表格填充颜色,两个for循环遍历来实现点对点。先用OpenCV把图像读取进来,rgb三通道分离。上代码!
import os
import cv2
from openpyxl import Workbook
from openpyxl.styles import PatternFill
def zero_filled(R1, G1, B1):
if len(R1) < 2:
R1 = "0" + R1
if len(G1) < 2:
G1 = "0" + G1
if len(B1) < 2:
B1 = "0" + B1
return R1 + G1 + B1
def file_name(file_dir):
for root, dirs, files in os.walk(file_dir):
print(root) # 当前目录路径
print(dirs) # 当前路径下所有子目录
print(files) # 当前路径下所有非目录子文件
# print(type(files))
return files
# 修改读入的文件名
img = cv2.imread("./IMAGES/2.JPG")
# 如果不需要黑白把A=0,默认A=1
A = 1
if A:
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
B = img[:, :, 0]
G = img[:, :, 1]
R = img[:, :, 2]
a, b, c = img.shape
# 行是a,列是b
# 创建工作簿
wb = Workbook()
# 获取默认的工作表
ws = wb.active
for row in range(a):
for column in range(b):
R_1 = hex(R[row][column])[2:]
G_1 = hex(G[row][column])[2:]
B_1 = hex(B[row][column])[2:]
HEX_color = zero_filled(R_1, G_1, B_1)
print(row, column, HEX_color)
# 设置单元格填充颜色和样式
pattern = PatternFill(fill_type='solid', start_color=HEX_color)
ws.cell(row=row + 1, column=column + 1).fill = pattern
# 自动保存为下一个文件
try:
i = file_name('xlsx')[-1][0:-5]
i = str(int(i) + 1)
print(i)
except ValueError and IndexError:
i = '0001'
if len(i) < 4:
i = '0' * (4 - len(i)) + i
print(i)
new_file = f'./xlsx/{i}.xlsx'
wb.save(new_file)
print(f"结束!新文件为{new_file}")
运行结果:
原图:
效果相当满意 !