Text angle from image

Hello,
I am trying to get the text angle from image using contours, PCACompute2, atan2.
But I am able to get only specific angle value correct(0 - 270).
I need detect all the angle values correct.
Your help would be highly appreciated.
Code -

def getOrientation(pts, img):
  ## [pca]
  # Construct a buffer used by the pca analysis
  sz = len(pts)
  data_pts = np.empty((sz, 2), dtype=np.float64)
  for i in range(data_pts.shape[0]):
    data_pts[i,0] = pts[i,0,0]
    data_pts[i,1] = pts[i,0,1]

  # Perform PCA analysis
  mean = np.empty((0))
  mean, eigenvectors, eigenvalues = cv.PCACompute2(data_pts, mean)

  # Store the center of the object
  cntr = (int(mean[0,0]), int(mean[0,1]))
  ## [pca]

  ## [visualization]
  # Draw the principal components
  cv.circle(img, cntr, 3, (255, 0, 255), 2)
  p1 = (cntr[0] + 0.02 * eigenvectors[0,0] * eigenvalues[0,0], cntr[1] + 0.02 * eigenvectors[0,1] * eigenvalues[0,0])
  p2 = (cntr[0] - 0.02 * eigenvectors[1,0] * eigenvalues[1,0], cntr[1] - 0.02 * eigenvectors[1,1] * eigenvalues[1,0])
  drawAxis(img, cntr, p1, (255, 255, 0), 1)
  drawAxis(img, cntr, p2, (0, 0, 255), 5)

  angle = atan2(eigenvectors[0,1], eigenvectors[0,0]) # orientation in radians
  ## [visualization]

  angle = np.rad2deg(angle)

  if angle > 0:
    angle = angle + 90
  else:
    angle = angle - 90

  # Label with the rotation angle
  label = str(int(angle)) + " degrees"
  textbox = cv.rectangle(img, (cntr[0], cntr[1]-25), (cntr[0] + 250, cntr[1] + 10), (255,255,255), -1)
  cv.putText(img, label, (cntr[0], cntr[1]), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1, cv.LINE_AA)

  return angle

see also the sample https://github.com/opencv/opencv/blob/4.x/samples/python/text_skewness_correction.py

1 Like

please explain, also take a close look at atan2 limitations

how do you know, that it’s the 2nd/3rd quadrant ? (imo, you can’t)

Thanks for your suggestion. I have tried sample examples its giving angle as zero. I think using skewness we can find the image rotated angle. I have tested on few image, getting the proper angle values for 1st, 2nd and 3rd quadrant.