大图裁剪再拼接(适用于tif png等多种图片)
import numpy as np
from PIL import Image
Image.MAX_IMAGE_PIXELS = 2500000000
import os
os.environ["OPENCV_IO_MAX_IMAGE_PIXELS"] = pow(2,40).__str__()
import cv2
import time
def cut_image(image):
box_list = []
for i in range(0,IMAGE_ROW + 1):
for j in range(0,IMAGE_COLUMN + 1):
if j == IMAGE_COLUMN and i == IMAGE_ROW:
box = (i * item_height, height, j * item_width, width)
elif j == IMAGE_COLUMN:
box = (i * item_height,(i + 1) * item_height, j * item_width, width)
elif i == IMAGE_ROW:
box = (i * item_height, height, j * item_width, (j + 1) * item_width)
else:
box = (i * item_height,(i + 1) * item_height, j * item_width, (j + 1) * item_width)
box_list.append(box)
image_list = [image[box[0]:box[1], box[2]:box[3]] for box in box_list]
return image_list
def save_images(image_list):
index = 0
for image in image_list:
cv2.imwrite('./img/'+str(index).zfill(6) + '.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 100])
index += 1
def image_compose():
IMAGES_PATH = 'img/'
IMAGES_FORMAT = ['.png']
IMAGE_SAVE_PATH = 'final.png'
to_image = Image.new('RGB', (width, height))
for y in range(0, IMAGE_ROW + 1):
for x in range(0, IMAGE_COLUMN + 1):
name = str((IMAGE_COLUMN + 1) * y + x).zfill(6) + '.png'
from_image = Image.open(IMAGES_PATH + name)
to_image.paste(from_image, (x * item_width, y * item_height))
return to_image.save(IMAGE_SAVE_PATH)
if __name__ == '__main__':
file_path = "result.tif"
start = time.time()
image = Image.open(file_path)
end = time.time()
print(end - start)
width, height = image.size
print(width, height)
item_width = 1280
IMAGE_ROW , IMAGE_COLUMN = height // item_width, width // item_width
print(IMAGE_ROW , IMAGE_COLUMN)
start = time.time()
image_list = cut_image(image)
end = time.time()
print(end - start)
start = time.time()
save_images(image_list)
end = time.time()
print(end - start)
start = time.time()
image_compose()
end = time.time()
print(end - start)