'Python - stitch images back together after slicing
I have a directory of image patches that are all the same size (33x33), the images are ordered so that the first 7 images are row 1, then the next 7 images are row 2, etc. I'm currently trying to reconstruct the original image using the 33x33 patches, but I am having trouble with the rows/cols organization. Any help with this is much appreciated! Here is my code for splitting the image into tiles:
def split_images():
img_arr = []
for image_path in image_paths:
image = cv2.imread(image_path, cv2.IMREAD_COLOR) # read in image
for i in range(0, image.shape[0], 33): # loop through height-wise pixels of image, striding by 33
for j in range(0, image.shape[1], 33): # loop through width-wise pixels of image, striding by 33
images = image[i:i + 33, j:j + 33, :] # creating label image from h,w pixel to 33 pixels to the right and down
img_arr.append(images) # create list from label images
# write images
cv2.imwrite(f"../outputs/subimages/subimage{i}_{j}.png", images)
return {"images": img_arr}
This splits the image into the aforementioned 33x33 tiles, but stitching them back together is where I'm having trouble. I can currently stitch the image back together in one long row, but I'm unsure of how to stitch the images back into their original order. This is my current stitching code:
def merge_images():
space_between_row = 10
new_image_path = 'result.jpg'
im_dirs = glob.glob('../outputs/subimages')
# get sorted list of images
im_path_list = [[path.join(p, f) for f in sorted(listdir(p))] for p in im_dirs]
# open images and calculate total widths and heights
im_list = []
total_width = 0
total_height = 0
for path_list in im_path_list:
images = list(map(Image.open, path_list))
widths, heights = zip(*(i.size for i in images))
total_width = max(total_width, sum(widths))
total_height += max(heights)
im_list.append(images)
# concat images
new_im = Image.new('RGB', (total_width, total_height))
y_offset = 0
for images in im_list:
x_offset = 0
max_height = 0
for im in images:
new_im.paste(im, (x_offset, y_offset))
x_offset += im.size[0]
max_height = max(im.size[1], max_height)
y_offset = y_offset + max_height + space_between_row
# show and save
new_im.show()
new_im.save(new_image_path)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
