【教学类-58-10】黑白三角拼图08(参考图+操作卡+黑白块,适合个别化)

bb22efa043144395827c84071d38fa33.png

背景需求:

前期做了一套适合集体操作的绘画“黑白三角”

【教学类-58-09】黑白三角拼图07(1页3张黑白的白点卡片,一种宫格36张,适合一个班级一次操作)-CSDN博客文章浏览阅读1k次,点赞30次,收藏7次。【教学类-58-09】黑白三角拼图07(1页3张黑白的白点卡片,一种宫格36张,适合一个班级一次操作)https://blog.csdn.net/reasonsummer/article/details/1393813829319e6882a094b44a5e29f396a6e937c.png

在小红书上的销售量最大

c904856932e24572bb1bd25e0f80d447.png

虽然有三款选择(黑白黏连、黑白有点、彩色有点),但是客户普遍选择基础款的“黑白黏连””

eec83ea13af64623b50772d0bd1cb687.png

昨天有一位客户求购后,提出新的需求:

297144d55e254b378ea6e5d1ab2334c0.png

客户觉得“左参考图右操作版”的样式打印太浪费纸

f4c97c84bc4f4a449a5e7d607e84828e.png客户以前购买我设计的三角图层

【教学类-55-03】20240512图层顺序挑战(三角形版)(6块三角形,49种叠放顺序)-CSDN博客文章浏览阅读1.1k次,点赞32次,收藏16次。【教学类-55-03】20240512图层顺序挑战(三角形版)(6块三角形,49种叠放顺序)https://blog.csdn.net/reasonsummer/article/details/138732291

5a7d740ed6f247d49cdf4512cac9ba42.png

41e5471cd0314c73ae3e0b67e669867f.png

客户希望能将“黑白三角参考图”单独做一份,空白格子底板和黑白三角块单独做一份,就是个别化学具(1-2人操作)

于是我微调了代码,并调试了word模板

510a8eabc99a4440b0780dcb9914e391.png

操作底板

48536e068c18482981976b24292c580a.png

80aa4101de804fa5a370324ae92b1535.png

参考图模版

57e3ce2130f24368a97db0d450f6320c.png

代码展示

'''

黑白三角图,2宫格36张,3宫格36张……适合个别化

随机图片
AI对话大师,阿夏
2024年8月16日

'''
import os,time
from PIL import Image, ImageDraw
from docx import Document
from docx.shared import Cm
from docx.shared import Pt
import shutil
import os
from PyPDF2 import PdfFileMerger  

# 几张(每张6图)
zhagnshu=6
# 起始宫格数
start=3
# 最大宫格数
end=10

path = r'C:\Users\jg2yXRZ\OneDrive\桌面\黑白三角单人款'


for gongge in range(start,end+1): # 遍历3宫格到10宫格
    for ys in range(zhagnshu,zhagnshu+1):
      
        new = path + fr'\{gongge:02}宫格组合图片'
        os.makedirs(new, exist_ok=True)
        radius = 5
        f = 6 * ys  # 一页6张

        b = 400  # 画布大小
        by = 10  # 边距

        print('----------1\制作白色操作图------------')
        for g in range(gongge,gongge+1):
            for c in range(1, f + 1):
                # 创建bxb的画布
                canvas = Image.new('RGB', (b, b), (255, 255, 255))
                draw = ImageDraw.Draw(canvas)

                # 定义表格的行数和列数、边距
                rows = g
                cols = g
                margin = by

                # 计算单元格的宽度和高度
                cell_width = (b - 2 * margin) // cols
                cell_height = (b - 2 * margin) // rows

                # 绘制表格的竖直线
                for i in range(cols + 1):
                    x = margin + i * cell_width
                    draw.line([(x, margin), (x, b - margin)], fill=(0, 0, 0), width=2)

                # 绘制表格的水平线
                for i in range(rows + 1):
                    y = margin + i * cell_height
                    draw.line([(margin, y), (b - margin, y)], fill=(0, 0, 0), width=2)

                # 绘制每个单元格的左上角、右上角、左下角、右下角的黑色圆形
                
                for i in range(rows):
                    for j in range(cols):
                        left = margin + j * cell_width
                        upper = margin + i * cell_height
                        right = left + cell_width
                        lower = upper + cell_height

                # 保存画布
                mb = f'{g:05d}格模板.png'
                canvas.save(new + fr'\{mb}')


                print('---2、制作黑白参考图,计算三个坐标点的黑色三角形不重复图案有几个-------')

                # 创建一个空列表用于存储单元格的坐标
                cell_coordinates = []

                # 计算每个单元格的四个顶点坐标
                for row in range(rows):
                    for col in range(cols):
                        top_left = (margin + col * cell_width, margin + row * cell_height)
                        top_right = (margin + (col + 1) * cell_width, margin + row * cell_height)
                        bottom_left = (margin + col * cell_width, margin + (row + 1) * cell_height)
                        bottom_right = (margin + (col + 1) * cell_width, margin + (row + 1) * cell_height)

                        
                        # 将四个顶点坐标添加到列表中
                        cell_coordinates.append([top_left, top_right, bottom_left, bottom_right])
                # print(cell_coordinates)
                # print(len(cell_coordinates))
                # 16
                # [[(0, 0), (400, 0), (0, 400), (400, 400)], [(400, 0), (b, 0), (400, 400), (b, 400)], [(0, 400), (400, 400), (0, b), (400, b)], [(400, 400), (b, 400), (400, b), (b, b)]]

                import random
                import os

                combinations=[]
                # 存储选取的点,随机生成坐标(样式)排除重复,生成10份样式不同的模版
                while len(combinations) < f:
                    selected_points = []
                    for points in cell_coordinates:
                        selected_points.append(tuple(random.sample(points, 3)))
                    combinations.append(tuple(selected_points))

                print(combinations)
                print(len(combinations))
                #  10

                print('---3、制作三个坐标点的黑色三角形(4个)-------')
                from PIL import Image, ImageDraw            
                # 定义要绘制的坐标点组合
                
                for point_combination in combinations:
                    print(point_combination)
                    
                    # 清空selected_points列表
                    selected_points = []
                    h=1
                    # 遍历每个坐标点组合
                    for combination in point_combination:
                        # 从每个列表中随机选取三个点,并加入到selected_points中
                        selected_points.append(tuple(random.sample(combination, 3)))

                            # 读取图像文件
    #                创建bxb的画布
                    canvas = Image.new('RGB', (b,b), (255, 255, 255))
                    draw = ImageDraw.Draw(canvas)

                    # 定义表格的行数和列数、边距
                    rows = g
                    cols = g
                    margin = by

                    # 计算单元格的宽度和高度
                    cell_width = (b - 2 * margin) // cols
                    cell_height = (b - 2 * margin) // rows

                    # 绘制表格的竖直线
                    for i in range(cols + 1):
                        x = margin + i * cell_width
                        draw.line([(x, margin), (x, b - margin)], fill=(0, 0, 0), width=2)

                    # 绘制表格的水平线
                    for i in range(rows + 1):
                        y = margin + i * cell_height
                        draw.line([(margin, y), (b - margin, y)], fill=(0, 0, 0), width=2)
                    color=['black','black']
                    # 遍历每个坐标点组合
                    for combination in selected_points:
                        # 绘制填充为黑色的多边形
                    
                        # draw.polygon(combination, fill='black',outline=(255, 255, 255), width=1)
                        draw.polygon(combination, fill=random.choice(color), outline=(0, 0, 0), width=2)

        

                    # 绘制每个单元格的左上角、右上角、左下角、右下角的黑色圆形
                
                    # 保存结果图像
                    canvas.save(new + fr'\{g:05d}格{c:05d}01图纸{c:05d}.png')
                    
                    canvas.close()  # 关闭图像文件
        
                            
        

        print('----4、贴图用黑色色块----------')
        canvas = Image.new('RGB', (b, b), (255, 255, 255))
        draw = ImageDraw.Draw(canvas)

        # 绘制表格的竖直线和水平线
        for i in range(cols + 1):
            x = margin + i * cell_width
            draw.line([(x, margin), (x, b - margin)], fill='black', width=2)

        for i in range(rows + 1):
            y = margin + i * cell_height
            draw.line([(margin, y), (b - margin, y)], fill='black', width=2)

        # 在每个单元格中绘制两个三角形
        for row in range(rows):
            for col in range(cols):
                left = margin + col * cell_width
                upper = margin + row * cell_height
                right = left + cell_width
                lower = upper + cell_height

                # 随机选择三个顶点坐标
                points = [(left, upper), (right, upper), (left, lower), (right, lower)]
                # random.shuffle(points)
                triangle1 = tuple(points[0:3])
                triangle2 = tuple(points[1:4])

                # 绘制三角形
                # 全部黑填充,白色边框
                draw.polygon(triangle1, fill='black',outline='white',width=2)
                draw.polygon(triangle2, fill='black',outline='white',width=2)
                # 全部黑色填充用黑色边框,白色填充用白色边框
                # draw.polygon(triangle1, fill='black',outline='black',width=2)
                # draw.polygon(triangle2, fill='white',outline='white',width=2)

        # 设置边框线为白色
        draw.line([(margin, margin), (b - margin, margin), (b - margin, b - margin), (margin, b - margin), (margin, margin)], fill='white', width=2)

        # 保存结果图像
        canvas.save(new + fr'\{g:05d}格黑块.png')
        canvas.close()




        print('---4合并打印------')


        # 第3步,读取图片写入docx,合并PDF

        import os,time
        from docx import Document
        from reportlab.lib.pagesizes import letter
        from reportlab.pdfgen import canvas
        from PyPDF2 import PdfMerger
        from docx.shared import Cm


        print('---5参考图合并-----')
        # 读取123文件夹中的所有图片地址(参考图)
        image_folder = new
        new_folder = path+r'\零时文件夹'
        os.makedirs(new_folder, exist_ok=True)
        image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

        new1=path+r'\保存1'
        os.makedirs(new1, exist_ok=True)

        # 每8个图片一组进行处理
        grouped_files = [image_files[:-2][i:i+6] for i in range(0, len(image_files[:-2]), 6)]
        print(grouped_files)

        # 处理每一组图片
        for group_index, group in enumerate(grouped_files):
            # 创建新的Word文档
            doc = Document(path+r'\模板6格.docx')
            print(group)
            
            # 遍历每个单元格,并插入图片
            for cell_index, image_file in enumerate(group):
                # 计算图片长宽(单位:厘米)
            
                
                # 插入图片到单元格
                table = doc.tables[0]
                cell = table.cell(int(cell_index / 2), cell_index % 2)
                # 6列两个都是6
                cell_paragraph = cell.paragraphs[0]
                cell_paragraph.clear()
                run = cell_paragraph.add_run()
                run.add_picture(image_file, width=Cm(9.4), height=Cm(9.4))
                
            # 保存Word文档
            doc.save(os.path.join(new_folder, f'{group_index + 1:03d}.docx'))
            

        # 所有docx合并成PDF

        # 将10个docx转为PDF
        import os
        from docx2pdf import convert
        from PyPDF2 import PdfFileMerger
        # from PyPDF4 import PdfMerger

        # output_folder = output_folder

        pdf_output_path = new1+fr'\02黑白三角{g:02d}宫格参考图.pdf'
    
        # 将所有DOCX文件转换为PDF
        for docx_file in os.listdir(new_folder):
            if docx_file.endswith('.docx'):
                docx_path = os.path.join(new_folder, docx_file)
                convert(docx_path, docx_path.replace('.docx', '.pdf'))
                time.sleep(1)


        # 合并零时文件里所有PDF文件
        merger = PdfFileMerger()
        for pdf_file in os.listdir(new_folder):
            if pdf_file.endswith('.pdf'):
                pdf_path = os.path.join(new_folder, pdf_file)
                merger.append(pdf_path)
        time.sleep(2)

        # 保存合并后的PDF文件
        merger.write(pdf_output_path)
        merger.close()

        import shutil
        # 删除输出文件夹
        import time
        shutil.rmtree(new_folder)
        # shutil.rmtree(new)
        time.sleep(2)


        print('---6答题卡合并(白图和黑三角卡片-----')
        # 读取123文件夹中的所有图片地址(参考图)
        image_folder = new
        new_folder = path+r'\零时文件夹'      
        os.makedirs(new_folder, exist_ok=True)
        
        image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

        # 每8个图片一组进行处理
        grouped_files = [image_files[-2:][i:i+2] for i in range(0, len(image_files[-2:]), 2)]
        print(grouped_files)

        for group_index, group in enumerate(grouped_files):
        # 创建新的Word文档
            doc = Document(path+r'\底图2格.docx')
            print(group)

            t=[f'黑白三角({gongge}宫格)操作卡',f'黑白三角({gongge}宫格)贴图卡']
            # 在单元格0,0写入“黑白三角(3宫格)操作卡”,24磅宋体
            for tt in range(len(t)):
                table = doc.tables[0]
                cell = table.cell(0, tt)
                cell_paragraph = cell.paragraphs[0]
                cell_paragraph.clear()
                run = cell_paragraph.add_run(t[tt])
                run.font.name = '宋体'
                run.font.size = Pt(24)
            
                    
            # 遍历每个单元格,并插入图片
            for cell_index, image_file in enumerate(group):
                # 计算图片长宽(单位:厘米)
                
                # 插入图片到单元格
                table = doc.tables[0]
                if cell_index == 0:
                    cell = table.cell(1, 0)
                elif cell_index == 1:
                    cell = table.cell(1, 1)
                else:
                    continue
                
                cell_paragraph = cell.paragraphs[0]
                cell_paragraph.clear()
                run = cell_paragraph.add_run()
                run.add_picture(image_file, width=Cm(14.2), height=Cm(14.2))
            
        # 保存Word文档
        doc.save(os.path.join(new_folder, f'{group_index + 1:03d}.docx'))

        
        # output_folder = output_folder

        pdf_output_path = new1+fr'\01黑白三角{g:02d}宫格黑块底图.pdf'
        # pdf_output_path = path+fr'\黑白三角1-10宫格随机每款{f*ys}图共{ys}张一黑一白黑点白边黑白.pdf'

        # 将所有DOCX文件转换为PDF
        for docx_file in os.listdir(new_folder):
            if docx_file.endswith('.docx'):
                docx_path = os.path.join(new_folder, docx_file)
                convert(docx_path, docx_path.replace('.docx', '.pdf'))
                time.sleep(1)

        # 合并零时文件里所有PDF文件
        merger = PdfFileMerger()
        for pdf_file in os.listdir(new_folder):
            if pdf_file.endswith('.pdf'):
                pdf_path = os.path.join(new_folder, pdf_file)
                merger.append(pdf_path)
        time.sleep(2)

        # 保存合并后的PDF文件
        merger.write(pdf_output_path)
        merger.close()

        
        # 删除输出文件夹
        
        shutil.rmtree(new_folder)
        shutil.rmtree(new)
        time.sleep(5)





        # print('---7合并答题卡和黑白三角卡片-----')
        t_folder = path+r'\pdf'
        os.makedirs(t_folder, exist_ok=True)
        
        pdf_output_path = t_folder + fr'\01黑白三角{g:02d}宫格{f}张参考图1套操作板.pdf'       
    
        # 合并零时文件里所有PDF文件
        merger = PdfFileMerger()
        for pdf_file in os.listdir(new1):
            if pdf_file.endswith('.pdf'):
                pdf_path = os.path.join(new1, pdf_file)
                merger.append(pdf_path)
                time.sleep(2)

        # 保存合并后的PDF文件
        merger.write(pdf_output_path)
        merger.close()

    
        # 删除输出文件夹
        
        shutil.rmtree(new1)
        # shutil.rmtree(new)
        time.sleep(2)

print('------3-10宫格全部打包-------')
# pdf_output_path = path + fr'\01黑白三角全黑块({start}-{end})宫格{zhagnshu*(end-start+1)}张参考图1套操作板.pdf'       
pdf_output_path = path + fr'\01黑白三角黑白块({start}-{end})宫格{zhagnshu*(end-start+1)}张参考图1套操作板.pdf'    
    
# 合并零时文件里所有PDF文件
merger = PdfFileMerger()
for pdf_file in os.listdir(t_folder):
    if pdf_file.endswith('.pdf'):
        pdf_path = os.path.join(t_folder, pdf_file)
        merger.append(pdf_path)
        time.sleep(2)

# 保存合并后的PDF文件
merger.write(pdf_output_path)
merger.close()


# 删除输出文件夹
shutil.rmtree(t_folder)




代码很长很长,有机会再优化一下。

caf9144db1504ec381e159e1aeebc69a.png

生成过程中会出现大量的零时文件夹,保存各种图、PDF。

415cf51addc646f082401f86fc27ceb6.png

1a67ad9d13af426a927db18895790e24.png

73567393f80941a296c39921d95cf3cf.png

0ef5c3446f7f4269b07d4f909818189e.png

5867dd32aed1420fbae67959566ee337.png

fafbd6adc7484e4dab44708bb88d5b13.png

f7c3d4667647405b8a482fde2c9fe12c.png

最终多个文件夹都会被删除,只保留最终的一个打包PDF。

35d397f00ccf40378712de33797de0e1.png

7460b253375147e28e4a79eb3f2fcefc.png

dc2a99171e484d9b94ee06e0d7db03af.png

223b05732aa84abaa1dfe62c08e2145d.png

由于底板图只有14CM款,所以只适合3宫格、4宫格,超过5宫格,格子就太多了,剪的黑白三角块也会很多

如果修改注释,还可以获得另一个版本的“黑白块”

6776ad9ff88240c98e97d9605bd60445.png

b70f10a1d2924563a60fe3bf542a7b8e.png

3d378a3b8aa6465daa82b02610a2c7cf.png9c6108b7dae844fdb5ec01528547d852.png

9db59eb842a742ab824c11ef6ea653db.png

b432bc3eb9cf404da2fcf40fb0af049c.png

最终客户选了第二种“黑白块“的样式

459c0dd7495349ad899e3868af573fbb.png

19d79d54dc0b46c1adbca702b0667372.png

057b8e4089dc4b09959905ded6a751ee.png

客户提到操作卡太小了,剪贴雌雄扣很费劲,所以我又调整了一版,把操作卡从一页2张,变成1页一张。

d423ce81375c43d181b5049492f74a66.png

e62dca55dcf9436c9f41f8b4a0d0bea9.png

02035a8972d84258b9ecd69c6d3fa6a6.png

代码展示:

'''

黑白三角图,2宫格36张,3宫格36张……适合个别化 大操作卡

随机图片
AI对话大师,阿夏
2024年8月16日

'''
import os,time
from PIL import Image, ImageDraw
from docx import Document
from docx.shared import Cm
from docx.shared import Pt
import shutil
import os
from PyPDF2 import PdfFileMerger  

# 几张(每张6图)
zhagnshu=6
# 起始宫格数
start=2
# 最大宫格数
end=10

path = r'C:\Users\jg2yXRZ\OneDrive\桌面\黑白三角单人款'



for gongge in range(start,end+1): # 遍历3宫格到10宫格
    for ys in range(zhagnshu,zhagnshu+1):
      
        new = path + fr'\{gongge:02}宫格组合图片'
        os.makedirs(new, exist_ok=True)
        radius = 5
        f = 6 * ys  # 一页6张

        b = 400  # 画布大小
        by = 10  # 边距

        print('----------1\制作白色操作图------------')
        for g in range(gongge,gongge+1):
            for c in range(1, f + 1):
                # 创建bxb的画布
                canvas = Image.new('RGB', (b, b), (255, 255, 255))
                draw = ImageDraw.Draw(canvas)

                # 定义表格的行数和列数、边距
                rows = g
                cols = g
                margin = by

                # 计算单元格的宽度和高度
                cell_width = (b - 2 * margin) // cols
                cell_height = (b - 2 * margin) // rows

                # 绘制表格的竖直线
                for i in range(cols + 1):
                    x = margin + i * cell_width
                    draw.line([(x, margin), (x, b - margin)], fill=(0, 0, 0), width=2)

                # 绘制表格的水平线
                for i in range(rows + 1):
                    y = margin + i * cell_height
                    draw.line([(margin, y), (b - margin, y)], fill=(0, 0, 0), width=2)

                # 绘制每个单元格的左上角、右上角、左下角、右下角的黑色圆形
                
                for i in range(rows):
                    for j in range(cols):
                        left = margin + j * cell_width
                        upper = margin + i * cell_height
                        right = left + cell_width
                        lower = upper + cell_height

                # 保存画布
                mb = f'{g:05d}格模板.png'
                canvas.save(new + fr'\{mb}')


                print('---2、制作黑白参考图,计算三个坐标点的黑色三角形不重复图案有几个-------')

                # 创建一个空列表用于存储单元格的坐标
                cell_coordinates = []

                # 计算每个单元格的四个顶点坐标
                for row in range(rows):
                    for col in range(cols):
                        top_left = (margin + col * cell_width, margin + row * cell_height)
                        top_right = (margin + (col + 1) * cell_width, margin + row * cell_height)
                        bottom_left = (margin + col * cell_width, margin + (row + 1) * cell_height)
                        bottom_right = (margin + (col + 1) * cell_width, margin + (row + 1) * cell_height)

                        
                        # 将四个顶点坐标添加到列表中
                        cell_coordinates.append([top_left, top_right, bottom_left, bottom_right])
                # print(cell_coordinates)
                # print(len(cell_coordinates))
                # 16
                # [[(0, 0), (400, 0), (0, 400), (400, 400)], [(400, 0), (b, 0), (400, 400), (b, 400)], [(0, 400), (400, 400), (0, b), (400, b)], [(400, 400), (b, 400), (400, b), (b, b)]]

                import random
                import os

                combinations=[]
                # 存储选取的点,随机生成坐标(样式)排除重复,生成10份样式不同的模版
                while len(combinations) < f:
                    selected_points = []
                    for points in cell_coordinates:
                        selected_points.append(tuple(random.sample(points, 3)))
                    combinations.append(tuple(selected_points))

                print(combinations)
                print(len(combinations))
                #  10

                print('---3、制作三个坐标点的黑色三角形(4个)-------')
                from PIL import Image, ImageDraw            
                # 定义要绘制的坐标点组合
                
                for point_combination in combinations:
                    print(point_combination)
                    
                    # 清空selected_points列表
                    selected_points = []
                    h=1
                    # 遍历每个坐标点组合
                    for combination in point_combination:
                        # 从每个列表中随机选取三个点,并加入到selected_points中
                        selected_points.append(tuple(random.sample(combination, 3)))

                            # 读取图像文件
    #                创建bxb的画布
                    canvas = Image.new('RGB', (b,b), (255, 255, 255))
                    draw = ImageDraw.Draw(canvas)

                    # 定义表格的行数和列数、边距
                    rows = g
                    cols = g
                    margin = by

                    # 计算单元格的宽度和高度
                    cell_width = (b - 2 * margin) // cols
                    cell_height = (b - 2 * margin) // rows

                    # 绘制表格的竖直线
                    for i in range(cols + 1):
                        x = margin + i * cell_width
                        draw.line([(x, margin), (x, b - margin)], fill=(0, 0, 0), width=2)

                    # 绘制表格的水平线
                    for i in range(rows + 1):
                        y = margin + i * cell_height
                        draw.line([(margin, y), (b - margin, y)], fill=(0, 0, 0), width=2)
                    color=['black','black']
                    # 遍历每个坐标点组合
                    for combination in selected_points:
                        # 绘制填充为黑色的多边形
                    
                        # draw.polygon(combination, fill='black',outline=(255, 255, 255), width=1)
                        draw.polygon(combination, fill=random.choice(color), outline=(0, 0, 0), width=2)

        

                    # 绘制每个单元格的左上角、右上角、左下角、右下角的黑色圆形
                
                    # 保存结果图像
                    canvas.save(new + fr'\{g:05d}格{c:05d}01图纸{c:05d}.png')
                    
                    canvas.close()  # 关闭图像文件
        
                            
        

        print('----4、贴图用黑色色块----------')
        canvas = Image.new('RGB', (b, b), (255, 255, 255))
        draw = ImageDraw.Draw(canvas)

        # 绘制表格的竖直线和水平线
        for i in range(cols + 1):
            x = margin + i * cell_width
            draw.line([(x, margin), (x, b - margin)], fill='black', width=2)

        for i in range(rows + 1):
            y = margin + i * cell_height
            draw.line([(margin, y), (b - margin, y)], fill='black', width=2)

        # 在每个单元格中绘制两个三角形
        for row in range(rows):
            for col in range(cols):
                left = margin + col * cell_width
                upper = margin + row * cell_height
                right = left + cell_width
                lower = upper + cell_height

                # 随机选择三个顶点坐标
                points = [(left, upper), (right, upper), (left, lower), (right, lower)]
                # random.shuffle(points)
                triangle1 = tuple(points[0:3])
                triangle2 = tuple(points[1:4])

                # 绘制三角形
                # 全部黑填充,白色边框
                # draw.polygon(triangle1, fill='black',outline='white',width=2)
                # draw.polygon(triangle2, fill='black',outline='white',width=2)
                # 全部黑色填充用黑色边框,白色填充用白色边框
                draw.polygon(triangle1, fill='black',outline='black',width=2)
                draw.polygon(triangle2, fill='white',outline='white',width=2)

        # 设置边框线为白色
        draw.line([(margin, margin), (b - margin, margin), (b - margin, b - margin), (margin, b - margin), (margin, margin)], fill='white', width=2)

        # 保存结果图像
        canvas.save(new + fr'\{g:05d}格黑块.png')
        canvas.close()




        print('---4合并打印------')


        # 第3步,读取图片写入docx,合并PDF

        import os,time
        from docx import Document
        from reportlab.lib.pagesizes import letter
        from reportlab.pdfgen import canvas
        from PyPDF2 import PdfMerger
        from docx.shared import Cm


        print('---5参考图合并-----')
        # 读取123文件夹中的所有图片地址(参考图)
        image_folder = new
        new_folder = path+r'\零时文件夹'
        os.makedirs(new_folder, exist_ok=True)
        image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

        new1=path+r'\保存1'
        os.makedirs(new1, exist_ok=True)

        # 每8个图片一组进行处理
        grouped_files = [image_files[:-2][i:i+6] for i in range(0, len(image_files[:-2]), 6)]
        print(grouped_files)

        # 处理每一组图片
        for group_index, group in enumerate(grouped_files):
            # 创建新的Word文档
            doc = Document(path+r'\模板6格.docx')
            print(group)
            
            # 遍历每个单元格,并插入图片
            for cell_index, image_file in enumerate(group):
                # 计算图片长宽(单位:厘米)
            
                
                # 插入图片到单元格
                table = doc.tables[0]
                cell = table.cell(int(cell_index / 2), cell_index % 2)
                # 6列两个都是6
                cell_paragraph = cell.paragraphs[0]
                cell_paragraph.clear()
                run = cell_paragraph.add_run()
                run.add_picture(image_file, width=Cm(9.4), height=Cm(9.4))
                
            # 保存Word文档
            doc.save(os.path.join(new_folder, f'{group_index + 1:03d}.docx'))
            

        # 所有docx合并成PDF

        # 将10个docx转为PDF
        import os
        from docx2pdf import convert
        from PyPDF2 import PdfFileMerger
        # from PyPDF4 import PdfMerger

        # output_folder = output_folder

        pdf_output_path = new1+fr'\02黑白三角{g:02d}宫格参考图.pdf'
    
        # 将所有DOCX文件转换为PDF
        for docx_file in os.listdir(new_folder):
            if docx_file.endswith('.docx'):
                docx_path = os.path.join(new_folder, docx_file)
                convert(docx_path, docx_path.replace('.docx', '.pdf'))
                time.sleep(1)


        # 合并零时文件里所有PDF文件
        merger = PdfFileMerger()
        for pdf_file in os.listdir(new_folder):
            if pdf_file.endswith('.pdf'):
                pdf_path = os.path.join(new_folder, pdf_file)
                merger.append(pdf_path)
        time.sleep(2)

        # 保存合并后的PDF文件
        merger.write(pdf_output_path)
        merger.close()

        import shutil
        # 删除输出文件夹
        import time
        shutil.rmtree(new_folder)
        # shutil.rmtree(new)
        time.sleep(2)


        print('---6答题卡合并(白图和黑三角卡片-----')
        # 读取123文件夹中的所有图片地址(参考图)
        image_folder = new
        new_folder = path+r'\零时文件夹'      
        os.makedirs(new_folder, exist_ok=True)
        
        image_files = [os.path.join(image_folder, file) for file in os.listdir(image_folder) if file.endswith('.png')]

        # 每8个图片一组进行处理
        grouped_files = [image_files[-2:][i:i+2] for i in range(0, len(image_files[-2:]), 2)]
        print(grouped_files)

        for group_index, group in enumerate(grouped_files):
        # 创建新的Word文档
            doc = Document(path+r'\底图1格.docx')
            print(group)

            t=[f'黑白三角({gongge}宫格)操作卡',f'黑白三角({gongge}宫格)贴图卡']
            # 在单元格0,0写入“黑白三角(3宫格)操作卡”,24磅宋体
            for tt in range(len(t)):             
                table = doc.tables[tt]                # 两张表格
                cell = table.cell(0, 0)
                cell_paragraph = cell.paragraphs[0]
                cell_paragraph.clear()
                run = cell_paragraph.add_run(t[tt])
                run.font.name = '宋体'
                run.font.size = Pt(40)
            
                    
            # 遍历每个单元格,并插入图片
            for cell_index, image_file in enumerate(group):
                # 计算图片长宽(单位:厘米)
                
                # 插入图片到单元格
                
                table = doc.tables[0]
                if cell_index == 0:
                    cell = table.cell(1, 0)
                table = doc.tables[1]
                if cell_index == 1:
                    cell = table.cell(1, 0)
                # else:
                #     continue
                
                cell_paragraph = cell.paragraphs[0]
                cell_paragraph.clear()
                run = cell_paragraph.add_run()
                run.add_picture(image_file, width=Cm(19.6), height=Cm(19.6))
            
        # 保存Word文档
        doc.save(os.path.join(new_folder, f'{group_index + 1:03d}.docx'))

        
        # output_folder = output_folder

        pdf_output_path = new1+fr'\01黑白三角{g:02d}宫格黑块底图.pdf'
        # pdf_output_path = path+fr'\黑白三角1-10宫格随机每款{f*ys}图共{ys}张一黑一白黑点白边黑白.pdf'

        # 将所有DOCX文件转换为PDF
        for docx_file in os.listdir(new_folder):
            if docx_file.endswith('.docx'):
                docx_path = os.path.join(new_folder, docx_file)
                convert(docx_path, docx_path.replace('.docx', '.pdf'))
                time.sleep(1)

        # 合并零时文件里所有PDF文件
        merger = PdfFileMerger()
        for pdf_file in os.listdir(new_folder):
            if pdf_file.endswith('.pdf'):
                pdf_path = os.path.join(new_folder, pdf_file)
                merger.append(pdf_path)
        time.sleep(2)

        # 保存合并后的PDF文件
        merger.write(pdf_output_path)
        merger.close()

        
        # 删除输出文件夹
        
        shutil.rmtree(new_folder)
        shutil.rmtree(new)
        time.sleep(5)





        # print('---7合并答题卡和黑白三角卡片-----')
        t_folder = path+r'\pdf'
        os.makedirs(t_folder, exist_ok=True)
        
        pdf_output_path2 = t_folder + fr'\01黑白三角{g:02d}宫格{f}张合并.pdf'       
    
        # 合并零时文件里所有PDF文件
        merger = PdfFileMerger()
        for pdf_file in os.listdir(new1):
            if pdf_file.endswith('.pdf'):
                pdf_path = os.path.join(new1, pdf_file)
                merger.append(pdf_path)
                time.sleep(2)

        # 保存合并后的PDF文件
        merger.write(pdf_output_path2)
        merger.close()

    
        # 删除输出文件夹
        
        shutil.rmtree(new1)
        # shutil.rmtree(new)
#         time.sleep(2)

print('------3-10宫格全部打包-------')
# pdf_output_path = path + fr'\01黑白三角全黑块({start}-{end})宫格{zhagnshu*(end-start+1)}张参考图1套操作板.pdf'       
pdf_output_path = path + fr'\01黑白三角_黑白块_操作大图({start}-{end})宫格{zhagnshu*(end-start+1)}张参考图1套操作板.pdf'    
    
# 合并零时文件里所有PDF文件
merger = PdfFileMerger()
for pdf_file in os.listdir(t_folder):
    if pdf_file.endswith('.pdf'):
        pdf_path = os.path.join(t_folder, pdf_file)
        merger.append(pdf_path)
        time.sleep(2)

# 保存合并后的PDF文件
merger.write(pdf_output_path)
merger.close()


# 删除输出文件夹
shutil.rmtree(t_folder)




a414d4e5fb214d2696d70a60a84f7351.png26616c384f0345c8829775214b3b9da6.png

从2宫格开始,一张A4的操作卡和一张A4贴图卡。

a783acfd77ec4e3a8d1d8e285a06a8d3.png

fd2381e86dfc43beb7c24fb8b6b26aa4.png

2750dfaf605c4a4a905943f287aab80b.png

91b59979ed324085b8d91dcf458887af.png

到10宫格时,每个黑白三角方块只有1.96CM宽,特别小,需要100个雌雄扣。感觉有点复杂。

bb22efa043144395827c84071d38fa33.png

f4e2bd4e9a7245b9aeb16e22bf9d9e21.png

大班3-7宫格差不多了。

  • 20
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先,我们需要一个三维模型,可以使用开源的模型库加载一个OBJ格式的模型文件。这里我使用了pywavefront库,可以使用pip进行安装。 ```python !pip install pywavefront ``` 然后,我们需要加载模型文件,并将其转换为点和面的列表。这里我使用了numpy和pywavefront库。 ```python import numpy as np import pywavefront # 加载模型文件 model = pywavefront.Wavefront("model.obj") # 获取点坐标列表 points = np.array(model.vertices) # 获取面列表,每个面由三个点组成 faces = [] for mesh in model.mesh_list: for face in mesh.faces: faces.append(face) faces = np.array(faces, dtype=int) ``` 接下来,我们需要使用OpenGL进行可视,并且实现交互操作。这里我使用了pyopengl库,可以使用pip进行安装。 ```python !pip install pyopengl ``` 首先,我们需要初始OpenGL。 ```python from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * # 初始OpenGL def init(): # 设置背景颜色为白色 glClearColor(1.0, 1.0, 1.0, 1.0) # 设置点大小为2 glPointSize(2.0) # 设置投影矩阵 glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(45.0, 1.0, 0.1, 100.0) # 设置模型视矩阵 glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) ``` 然后,我们需要实现绘制函数。 ```python # 绘制函数 def draw(): # 清除颜色缓冲区和深度缓冲区 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # 绘制三角网格 glBegin(GL_TRIANGLES) for face in faces: glVertex3fv(points[face[0]]) glVertex3fv(points[face[1]]) glVertex3fv(points[face[2]]) glEnd() # 刷新缓冲区 glutSwapBuffers() ``` 最后,我们需要实现交互操作。 ```python # x轴旋转角度 xrot = 0.0 # y轴旋转角度 yrot = 0.0 # 鼠标按下时的坐标 xdown = 0 ydown = 0 # 鼠标是否按下 mousedown = False # 鼠标按下事件 def mouse_down(x, y): global xdown, ydown, mousedown xdown = x ydown = y mousedown = True # 鼠标移动事件 def mouse_move(x, y): global xrot, yrot, xdown, ydown, mousedown if mousedown: xrot += y - ydown yrot += x - xdown xdown = x ydown = y # 鼠标松开事件 def mouse_up(x, y): global mousedown mousedown = False # 键盘事件 def keyboard(key, x, y): global xrot, yrot if key == b'+': glTranslatef(0.0, 0.0, -0.1) elif key == b'-': glTranslatef(0.0, 0.0, 0.1) elif key == b'q': xrot -= 5.0 elif key == b'w': xrot += 5.0 elif key == b'a': yrot -= 5.0 elif key == b's': yrot += 5.0 # 初始GLUT窗口 glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(500, 500) glutCreateWindow("3D Model Viewer") # 注册回调函数 glutDisplayFunc(draw) glutMouseFunc(mouse_down) glutMotionFunc(mouse_move) glutKeyboardFunc(keyboard) # 启用深度测试 glEnable(GL_DEPTH_TEST) # 开始事件循环 init() glutMainLoop() ``` 这里实现了鼠标拖动旋转模型和键盘按键移动模型的交互操作。你可以在控制台中按下“+”或“-”键来移动模型,按下“q”、“w”、“a”、“s”键来旋转模型。 完整代码如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿夏reasonsummer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值