title: Find orientation of object using PCA
body: <p><img src="https://i.stack.imgur.com/hIJDR.png" alt="image 1"></p>
  
  <p><img src="https://i.stack.imgur.com/aObgb.png" alt="image 2"></p>
  
  <p>I want to find the orientation of the bright object in the images attached. For this purpose, I used Principal Component Analysis(PCA).</p>
  
  <p>In case of image 1, PCA finds correct orientation as the first principal component is alligned in that direction. However, in case of image 2, the principal components are disoriented.</p>
  
  <p>Can anyone please explain why the PCA is showing different results in the two images? Also, please suggest if there is some other method to find the orientation of the object. </p>
  
  <pre><code>import os
  import gdal
  import matplotlib
  import matplotlib.pyplot as plt
  import numpy as np
  import skimage
  from skimage.filters import threshold_otsu
  from skimage.filters import try_all_threshold
  import cv2
  import math
  from skimage import img_as_ubyte
  from skimage.morphology import convex_hull_image
  import pandas as pd  
  
  file="path to image file"
  
  (fileRoot, fileExt)= os.path.splitext(file)
  
  ds = gdal.Open(file)
  band = ds.GetRasterBand(1)
  arr = band.ReadAsArray()
  geotransform = ds.GetGeoTransform()   
  [cols, rows] = arr.shape
  thresh = threshold_otsu(arr)
  binary = arr &gt; thresh
  points = binary&gt;0
  y,x = np.nonzero(points) 
  x = x - np.mean(x)
  y = y - np.mean(y)
  coords = np.vstack([x, y])
  cov = np.cov(coords)
  evals, evecs = np.linalg.eig(cov)
  sort_indices = np.argsort(evals)[::-1]
  evec1, evec2 = evecs[:, sort_indices]
  x_v1, y_v1 = evec1  
  x_v2, y_v2 = evec2
  scale = 40
  plt.plot([x_v1*-scale*2, x_v1*scale*2],
           [y_v1*-scale*2, y_v1*scale*2], color='red')
  plt.plot([x_v2*-scale, x_v2*scale],
           [y_v2*-scale, y_v2*scale], color='blue')
  plt.plot(x,y, 'k.')
  plt.axis('equal')
  plt.gca().invert_yaxis()  
  plt.show()
  theta = np.tanh((x_v1)/(y_v1))  * 180 /(math.pi)
  </code></pre>