利用python opencv2进行多图片摘要

概述

实现将一个目录内的多个图片摘要到一张图片内,效果如下:利用python opencv2进行多图片摘要_第1张图片

设计思路

1.图片读取,根据图片进行缩放
2.将多张缩略图片进行拼接
网络上能查到使用PIL实现的,使用的是image的paste方法,整个程序流程是一样的。

开发重点

1)文件预处理

pfilename={'.jpg':'','.JPG':'','.jpeg':'','.png':'','.PNG':''}
fs=os.listdir(dir_name)
for f in fs:
	if os.path.splitext(f)[1] in pfilename:
    	imgfs.append(os.path.join(dir_name,f))

这里对文件扩展名进行预处理,防止文件内其它文件对后续处理造成干扰
2)生成目标画布

per_row=8 #每行8个
per_w=200 #缩略图宽200
per_int=5 #间隔5
dis_w=per_row*per_w+(per_row+1)*per_int #目标宽
n_h=math.ceil(len(imgfs)/per_row)
    img=cv2.imdecode(np.fromfile(imgfs[0],dtype=np.uint8),cv2.IMREAD_COLOR)

per_h=math.ceil(img.shape[0]/img.shape[1]*per_w)
dis_h=n_h*per_h+(n_h+1)*per_int#目标高
dis_img = np.zeros((dis_h,dis_w,3), np.uint8)
dis_img.fill(255) #填白

这里计算目标画布大小,需要读第一个文件出来作为参照,当然对文件内图片大小不一的会造成拉伸的变形

3)缩略,拼接

idx_x=per_int
idx_y=per_int

for f in imgfs:
     	img=cv2.imdecode(np.fromfile(f,dtype=np.uint8),cv2.IMREAD_COLOR)

        r_img=cv2.resize(img,(per_w,per_h))

        if idx_x>=dis_w:

            idx_x=per_int
            idx_y+=per_h
            idx_y+=per_int

        for i in range(0,r_img.shape[0]):
            for j in range(0,r_img.shape[1]):
                dis_img[idx_y+i][idx_x+j]=r_img[i][j]
        idx_x+=per_w
        idx_x+=per_int
#cv2.imshow('dis_img', dis_img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

写入就是循环替换像素了
##问题总结
opencv的图像数据结构是[高,宽],和通常的[宽,高]是相反的,这点初学者很容易搞错,用多就好了。

你可能感兴趣的:(python,图像处理,opencv)