I would like to rotate an image (such as the one below) in a way that one of its features (which resembles a line) becomes vertical. However, I can't seem to find a way to programmatically do it in Python. Example_Image
1 Answer
The rotation itself can be done by the scipy.ndimage.interpolation.rotate operation.
The following first part is solving the issue for the example scenario in the original question (having one elongated data blob), see below for a more general (but slower) approach. Hope this helps!
First Approach: To find the axis and with that the angle of your line I suggest to use a PCA on the non-zero values:
from scipy.ndimage.interpolation import rotate
#from skimage.transform import rotate ## Alternatively
from sklearn.decomposition.pca import PCA ## Or use its numpy variant
import numpy as np
def verticalize_img(img):
"""
Method to rotate a greyscale image based on its principal axis.
:param img: Two dimensional array-like object, values > 0 being interpreted as containing to a line
:return rotated_img:
"""# Get the coordinates of the points of interest:
X = np.array(np.where(img > 0)).T
# Perform a PCA and compute the angle of the first principal axes
pca = PCA(n_components=2).fit(X)
angle = np.arctan2(*pca.components_[0])
# Rotate the image by the computed angle:
rotated_img = rotate(img,angle/pi*180-90)
return rotated_img
As usually this function could also be written as one-liner:
rotated_img = rotate(img,np.arctan2(*PCA(2).fit(np.array(np.where(img > 0)).T).components_[0])/pi*180-90)
And here is an example:
from matplotlib import pyplot as plt
# Example data:
img = np.array([[0,0,0,0,0,0,0],
[0,1,0,0,0,0,0],
[0,0,1,1,0,0,0],
[0,0,0,1,1,0,0],
[0,0,1,0,0,1,0],
[0,0,0,0,0,0,1]])
# Or alternatively a straight line:
img = np.diag(ones(15))
img = np.around(rotate(img,25))
# Or a distorted blob:
from sklearn import cluster, datasets
X, y = datasets.make_blobs(n_samples=100, centers = [[0,0]])
distortion = [[0.6, -0.6], [-0.4, 0.8]]
theta = np.radians(20)
rotation = np.array(((cos(theta),-sin(theta)), (sin(theta), cos(theta))))
X = np.dot(np.dot(X, distortion),rotation)
img = np.histogram2d(*X.T)[0] # > 0 ## uncomment for making the example binary
rotated_img = verticalize_img(img)
# Plot the results
plt.matshow(img)
plt.title('Original')
plt.matshow(rotated_img)
plt.title('Rotated'))
Note that for highly noisy data or images with no clear orientation this method will come up with arbitrary rotations.
And here is an example output:
Second Approach: Ok after clarification of the actual task in a more complicated setting (see comments) here a second approach based on template matching:
from matplotlib import pyplot as plt
import numpy as np
import pandas
from scipy.ndimage.interpolation import rotate
from scipy.signal import correlate2d#, fftconvolve
# Data from CSV file:
img = pandas.read_csv('/home/casibus/testdata.csv')
# Create a template:
template = np.zeros_like(img.values)
template[:,int(len(template[0])*1./2)] = 1
suggested_angles = np.arange(0,180,1) # Change to any resolution you like
overlaps = [np.amax(correlate2d(rotate(img,alpha,reshape=False),template,mode='same')) for alpha in suggested_angles]
# Determine the angle resulting in maximal overlap and rotate:
rotated_img = rotate(img.values,-suggested_angles[np.argmax(overlaps)])
plt.matshow(rotated_img)
plt.matshow(template)
-
Dear Jojo, thank you very much for your detailed answer. It seems to solve the problem but It fails for noisy data (as you mention), which is most of my data unfortunately. Dec 19, 2018 at 22:05
-
-
-
Ok, that of course is a very different situation. Here you have multiple stripes and to get my function to work you would need to extract one of the stripes first. Here is a very practical approach: I suggest to use a template (i.e. a vertical line image) and rotate your data as long as the overlap (in terms of the peak value scipy.signal.correlation2d) is maximized. This gives you the angle. I might find time to work it out for you later in case you have problems.– JojoDec 20, 2018 at 13:36
-
Here you go! I did not test it for different examples, there could be a mistake in the way how it is rotated in the end. In that case try to remove the minus. Hope it helps.– JojoDec 20, 2018 at 13:59