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() #調用函數