Skip to content
Advertisement

Reconstruct Image from patches/tiles in python

I have a task where I have tiled an Input image using the code:

def tileImage(img,numrows,numcols,show = False):
    height = int(img.shape[0] / numrows)
    width = int(img.shape[1] / numcols)
    tiles = []
    for row in range(numrows):
        for col in range(numcols):
            y0 = row * height
            y1 = y0 + height
            x0 = col * width
            x1 = x0 + width
            tiles.append(img[y0:y1, x0:x1])
            if show:
                cv2.imshow("tile",img[y0:y1, x0:x1])
                cv2.rectangle(img,(x0,y0),(x1,y1),(255),1)
                cv2.imshow("Tile",img)
                cv2.waitKey(0)
                cv2.destroyAllWindows
    return tiles

After that I calculated the sum of all tiles and sort them in ascending order. I’ll take the sum.sorted[-20] as a threshold and set all tiles below that threshold to 0 in order to neglect background. So far everything works fine.

Now I need to reconstruct the image using the tiles. I tried np.reshape.

shutOffTiles = np.reshape(thresholded,(height*numrows,width*numcols,1))

The dimensions are OK. However, the results look like this due to the order of the tiles Reconstruction

I also tried to flatten the tiles and reshape them. Has anybody a proper solution with the indexing? Thank you very much in advance

with the solution of @Paul Panzer

thresholded.reshape(numrows, numcols, height, width).swapaxes(1, 2).reshape(height*numrows, width*numcols, 1)

I get: enter image description here

Advertisement

Answer

It turns out two ingredients were needed.

1) Geometry:

Since the tiles when embedded in the original image are not memory contiguous (for example after the first row of the top left tile comes the first row of the next tile) a simple reshape won’t work. Instead we must first split the zeroth axis (the one that enumerates tiles) into rows and columns. Then we must move the two horizontal and the two vertical axes next to each other in each case the tile dimension must come last. Finally, we can combine the two pairs into one axis each and add a new axis on the right.

thresholded.reshape(numrows, numcols, height, width).swapaxes(1, 2).reshape(height*numrows, width*numcols, 1)

2) Normalization.

Apparently, there was a mismatch between the processing and the visualisation that could be fixed by normalizing – OP understands that better than me.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement