1.图片分块
import os import matplotlib.pyplot as plt import cv2 import numpy as np def divide_img(img_path, img_name, save_path): imgg=img_path+img_name img = cv2.imread(imgg) # img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) h = img.shape[0] w = img.shape[1] n=8 m=8 print('h={},w={},n={},m={}'.format(h,w,n,m)) dis_h=int(np.floor(h/n)) dis_w=int(np.floor(w/m)) num=0 for i in range(n): for j in range(m): num+=1 print('i,j={}{}'.format(i,j)) sub=img[dis_h*i:dis_h*(i+1),dis_w*j:dis_w*(j+1),:] cv2.imwrite(save_path + '_{}.tif'.format(num),sub) if __name__ == '__main__': img_path = 'D:\PycharmDOC\divide_test_photo\s1\' save_path = 'D:\PycharmDOC\divide_test_photo\s2\' img_list = os.listdir(img_path) for name in img_list: divide_img(img_path,name,save_path)
2.图片拼接
import PIL.Image as Image import os IMAGES_PATH = 'D:\PycharmDOC\divide_test_photo\s3\' # 图片集地址 IMAGES_FORMAT = ['.jpg', '.tif'] # 图片格式 IMAGE_SIZE = 128 # 每张小图片的大小 IMAGE_ROW = 8 # 图片间隔,也就是合并成一张图后,一共有几行 IMAGE_COLUMN = 8 # 图片间隔,也就是合并成一张图后,一共有几列 IMAGE_SAVE_PATH = 'D:\PycharmDOC\divide_test_photo\pj.tif' # 图片转换后的地址 # 获取图片集地址下的所有图片名称 image_names = [name for name in os.listdir(IMAGES_PATH) for item in IMAGES_FORMAT if os.path.splitext(name)[1] == item] # 简单的对于参数的设定和实际图片集的大小进行数量判断 if len(image_names) != IMAGE_ROW * IMAGE_COLUMN: raise ValueError("合成图片的参数和要求的数量不能匹配!") # 定义图像拼接函数 def image_compose(): to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_SIZE, IMAGE_ROW * IMAGE_SIZE)) #创建一个新图 # 循环遍历,把每张图片按顺序粘贴到对应位置上 for y in range(1, IMAGE_ROW + 1): for x in range(1, IMAGE_COLUMN + 1): from_image = Image.open(IMAGES_PATH + image_names[IMAGE_COLUMN * (y - 1) + x - 1]).resize( (IMAGE_SIZE, IMAGE_SIZE),Image.ANTIALIAS) to_image.paste(from_image, ((x - 1) * IMAGE_SIZE, (y - 1) * IMAGE_SIZE)) return to_image.save(IMAGE_SAVE_PATH) # 保存新图 image_compose() #调用函数