I split my image (Raster image) into 1000 tiles for image segmentation prediction, and I want to mosaic the predicted rasters to a 1664*2432 grid sequentially. I used these posts:
Generate a Photographic mosaic from a given set of thumbnails
How do you merge images into a canvas using PIL/Pillow?
PIL fill background image repeatedly
This is the code:
import PIL, os, glob
from PIL import Image
from math import ceil, floor
PATH = '/content/drive/MyDrive/classification/CNN_segmentation/big_Image/prediction'
frame_width = 1664
images_per_row = 26
padding = 2
os.chdir(PATH)
images = glob.glob("*.tiff")
images = images[:988]
img_width, img_height = Image.open(images[0]).size
sf = (frame_width-(images_per_row-1)*padding)/(images_per_row*img_width) #scaling factor
scaled_img_width = ceil(img_width*sf) #s
scaled_img_height = ceil(img_height*sf)
number_of_rows = 38
frame_height = 2432
new_im = Image.new('RGB', (frame_width, frame_height))
i,j=0,0
for num, im in enumerate(images):
if num%images_per_row==0:
i=0
im = Image.open(im)
im.thumbnail((64,64))
#Iterate through a 4 by 4 grid with 100 spacing, to place my image
y_cord = (j//images_per_row)*scaled_img_height
new_im.paste(im, (i,y_cord))
i=(i+64)+0
j+=1
new_im.show()
new_im.save("out.jpg", "JPEG", quality=80, optimize=True, progressive=True)
new_im
The result is a 1664*2432 image but all the pixels are black. I tried to use, "im=rasterio.open(im)" instead of "im = Image.open(im)", but I faced this error:
AttributeError: 'DatasetReader' object has no attribute 'thumbnail'
I will be thankful if anybody could help me.
Note: I solved the problem by replacing RGB with P, but still do not know how mosaic the images by file name sequentially.