text_skewness_correction.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. '''
  2. Text skewness correction
  3. This tutorial demonstrates how to correct the skewness in a text.
  4. The program takes as input a skewed source image and shows non skewed text.
  5. Usage:
  6. python text_skewness_correction.py --image "Image path"
  7. '''
  8. import numpy as np
  9. import cv2 as cv
  10. import sys
  11. import argparse
  12. def main():
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument("-i", "--image", default="imageTextR.png", help="path to input image file")
  15. args = vars(parser.parse_args())
  16. # load the image from disk
  17. image = cv.imread(cv.samples.findFile(args["image"]))
  18. if image is None:
  19. print("can't read image " + args["image"])
  20. sys.exit(-1)
  21. gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
  22. # threshold the image, setting all foreground pixels to
  23. # 255 and all background pixels to 0
  24. thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]
  25. # Applying erode filter to remove random noise
  26. erosion_size = 1
  27. element = cv.getStructuringElement(cv.MORPH_RECT, (2 * erosion_size + 1, 2 * erosion_size + 1), (erosion_size, erosion_size) )
  28. thresh = cv.erode(thresh, element)
  29. coords = cv.findNonZero(thresh)
  30. angle = cv.minAreaRect(coords)[-1]
  31. # the `cv.minAreaRect` function returns values in the
  32. # range [0, 90) if the angle is more than 45 we need to subtract 90 from it
  33. if angle > 45:
  34. angle = (angle - 90)
  35. (h, w) = image.shape[:2]
  36. center = (w // 2, h // 2)
  37. M = cv.getRotationMatrix2D(center, angle, 1.0)
  38. rotated = cv.warpAffine(image, M, (w, h), flags=cv.INTER_CUBIC, borderMode=cv.BORDER_REPLICATE)
  39. cv.putText(rotated, "Angle: {:.2f} degrees".format(angle), (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  40. # show the output image
  41. print("[INFO] angle: {:.2f}".format(angle))
  42. cv.imshow("Input", image)
  43. cv.imshow("Rotated", rotated)
  44. cv.waitKey(0)
  45. if __name__ == "__main__":
  46. print(__doc__)
  47. main()
  48. cv.destroyAllWindows()