python openpyxl实现电子十字绣

上班摸鱼电子用表格电子十字绣打发时间确实是个好法子,但是以前刚好用过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}")

运行结果:

 

原图:

c7b0345e75544b1d91a3907332a6b55d.png

效果相当满意 !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值