2019年11月14号
作者:杨轮飞
前几天遇到一个小问题,收到了大概一百五十张大小不一致的照片,要将其放入到docx文档中,如果一张一张放进去,还得一张一张的去调图片大小,实在是太麻烦了,写个处理排版的代码就一劳永逸了~
先导入库:进度条、opencv、os和numpy
from tqdm import trange
import cv2
import os
import numpy as np
思路是将四张图片排在一张A4大小的背景图里,所以先写一个能够返回四个图像在背景上的左上角坐标,输出参数分别是背景图像和目标图像的行数和列数
def image_site(back, up):
height, weight = back
row, col = up
pointy1 = int((height/2 - row)/2)
pointx1 = int((weight/2 - col)/2)
return [(pointx1, pointy1), (col + pointx1 * 3, pointy1), (pointx1, row + pointy1*3), (col + pointx1 * 3, row + pointy1*3)]
在接下来写一个将图片放入背景图的函数
def image_add(background, images, points, imagesize):
row, col = imagesize
for number in range(len(images)):
point = points[number]
background[point[1]:point[1]+row, point[0]:point[0]+col] = images[number]
return background
每处理好四张图像就需要放入背景图中,所以再写一个创建空白背景图的函数
# BGR
def create_image(row, col, color):
image = np.zeros([row, col, 3], np.uint8)
image[:, :, 0] = np.zeros([row, col]) + color[0]
image[:, :, 1] = np.zeros([row, col]) + color[1]
image[:, :, 2] = np.zeros([row, col]) + color[2]
return image
接下来就是主函数了,每读取四张图像,就将其添加到背景图中,并保存,该文件执行后生成一些合成图像
if __name__ == '__main__':
file = 'card'
endfile = 'result'
filelist = os.listdir(file)
color = (255, 255, 255)
height, weight = 835, 595
row, col = 395, 280
points = image_site((height, weight), (row, col))
print("标点位置:",points)
image_PDF = []
for number in trange(0,len(filelist)-3):
if (number+4) % 4 == 0:
background = create_image(height, weight, color)
images = []
for image_min_number in range(4):
img = cv2.imdecode(np.fromfile(file + '\\' + filelist[image_min_number+number], dtype=np.uint8), 1)
img = cv2.resize(img, (col, row), interpolation=cv2.INTER_AREA)
images.append(img)
result = image_add(background, images, points, (row, col))
#result = cv2.resize(result, (350, 500), interpolation=cv2.INTER_AREA)
cv2.imwrite(endfile+'\\'+str(number)+'.jpg',result,[int(cv2.IMWRITE_JPEG_QUALITY),100])
image_PDF.append(result)
#cv2.imshow("111", result)
#cv2.waitKey()
cv2.waitKey(10)
print("合成纸张数量:",len(image_PDF))
生成图像后就简单多了,只要将其添加到文档中就行了,因为没有找到修改docx文档的页边距的函数,所以只能退而求其次,创建一个docx文档,设置好页边距后进行添加了。
from docx import Document
from tqdm import trange
import os
#
def main():
document = Document('demo.docx')
file = 'result'
filelist = os.listdir(file)
for t in trange(len(filelist)):
document.add_picture(file+'\\'+filelist[t])
document.save('demo.docx')
if __name__ == '__main__':
main()
最终效果如下