Skip to content

Instantly share code, notes, and snippets.

@pantor
Last active November 30, 2017 14:25
Show Gist options
  • Save pantor/6094d0259938bd5c190c3fb19f89c0d3 to your computer and use it in GitHub Desktop.
Save pantor/6094d0259938bd5c190c3fb19f89c0d3 to your computer and use it in GitHub Desktop.
Images Transformation
#!/usr/bin/python2
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from skimage import transform
path = '' # TODO Fill path
file1 = 'LM15_aussen_mark_4x.tiff'
file2 = 'heatmap2.tiff'
output_filename = 'test.png'
# Load images
img1 = io.imread(os.path.join(path, file1))
img2 = io.imread(os.path.join(path, file2))
# Show images
fig, ax = plt.subplots(ncols=3, figsize=(15, 6))
ax[0].imshow(img1, picker=True)
ax[0].set_title('Image 1')
ax[1].imshow(img2, picker=True)
ax[1].set_title('Image 2')
ax[2].set_title('Reconstructed Image 1')
plt.tight_layout()
# Points data structure
img_points = {
0: [], # Image 1
1: [], # Image 2
}
def on_click(event):
# Save points in subplot list
point = [event.mouseevent.xdata, event.mouseevent.ydata]
subplot = np.where(ax == event.artist.axes)[0][0]
img_points[subplot].append(point)
# Print and add label in image
print('New event at x={} y={} subplot={}'.format(point[0], point[1], subplot))
ax[subplot].scatter(point[0], point[1], color='red', s=20)
ax[subplot].text(point[0] + 12, point[1] + 12, str(len(img_points[subplot])), color='red', fontsize=13)
# Calculate transformation, show and save image
if len(img_points[0]) > 2 and len(img_points[0]) == len(img_points[1]):
transformation = transform.estimate_transform('similarity', np.array(img_points[0]), np.array(img_points[1]))
reconstructed_img = transform.warp(img2, transformation, output_shape=img1.shape)
ax[2].cla() # Clear subplot
ax[2].imshow(reconstructed_img)
ax[2].set_xlim(0, reconstructed_img.shape[1]) # Limits are somehow not set automatically
ax[2].set_ylim(reconstructed_img.shape[0], 0)
io.imsave(os.path.join(path, output_filename), reconstructed_img)
else:
print('Need either more points or the same number of points on each image.')
plt.show()
fig.canvas.mpl_connect('pick_event', on_click)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment