March Ho March Ho - 2 years ago 153
Python Question

Most pythonic way to stitch an array of images together

I have an array of images from an automated microscope program acquiring images from a 96 well plate (image below). Each image is named as:

<Well name>_s<site number>.tif

Each well of the 96 well plate is further subdivided into sites, the sites are arranged in an X by Y matrix, and the numbers are arranged line by line (image below).

96 well plate layout

Site layout

For example, an image in the (10,9)th site of the top left well in the 96 well plate would be named

What is the most Pythonic way to stitch the images together? I am currently using OpenCV to load the images and calling
in four
loops, but this seems very unwieldy.

Answer Source

Something like the code below? I'm assuming that it's the stitching that's the problem, not the translation between filenames and well/site indices.

import numpy as np
import matplotlib.pyplot as plt

img_xsize, img_ysize = 20, 20 # size of single image
mx, my = 10, 10 # x/y grid of sites per well
nx, ny = 12, 8 # x/y grid of wells per plate
wgap = 20 # pixels gap between wells
stitched_x, stitched_y = (wgap+mx*img_xsize)*nx, (wgap+my*img_ysize)*ny

img_stitched = np.zeros((stitched_y, stitched_x), dtype=np.uint8)

def add_img(mxi, myi, nxi, nyi, img):
    assert img.shape == (img_ysize, img_xsize)
    xi = nxi*(mx*img_xsize + wgap) + mxi*img_xsize
    yi = nyi*(my*img_ysize + wgap) + myi*img_ysize
    img_stitched[yi:yi+img_ysize,xi:xi+img_xsize] = img

for nxi in range(nx):
    for nyi in range(ny):
        for mxi in range(mx):
            for myi in range(my):
                # ... get image data
                img = np.random.randint(0,255) * np.ones((img_ysize, img_xsize), dtype=np.uint8)
                add_img(mxi, myi, nxi, nyi, img)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download