File: text_skewness_correction.py

package info (click to toggle)
opencv 4.5.1%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 268,248 kB
  • sloc: cpp: 969,170; xml: 682,525; python: 36,732; lisp: 30,170; java: 25,155; ansic: 7,927; javascript: 5,643; objc: 2,041; sh: 935; cs: 601; perl: 494; makefile: 145
file content (58 lines) | stat: -rw-r--r-- 1,937 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'''
Text skewness correction
This tutorial demonstrates how to correct the skewness in a text.
The program takes as input a skewed source image and shows non skewed text.

Usage:
        python text_skewness_correction.py --image "Image path"
'''

import numpy as np
import cv2 as cv
import sys
import argparse


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--image", required=True, help="path to input image file")
    args = vars(parser.parse_args())

    # load the image from disk
    image = cv.imread(cv.samples.findFile(args["image"]))
    if image is None:
        print("can't read image " + args["image"])
        sys.exit(-1)
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    # threshold the image, setting all foreground pixels to
    # 255 and all background pixels to 0
    thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]

    # Applying erode filter to remove random noise
    erosion_size = 1
    element = cv.getStructuringElement(cv.MORPH_RECT, (2 * erosion_size + 1, 2 * erosion_size + 1), (erosion_size, erosion_size) )
    thresh = cv.erode(thresh, element)

    coords = cv.findNonZero(thresh)
    angle = cv.minAreaRect(coords)[-1]
    # the `cv.minAreaRect` function returns values in the
    # range [-90, 0) if the angle is less than -45 we need to add 90 to it
    if angle < -45:
        angle = (90 + angle)

    (h, w) = image.shape[:2]
    center = (w // 2, h // 2)
    M = cv.getRotationMatrix2D(center, angle, 1.0)
    rotated = cv.warpAffine(image, M, (w, h), flags=cv.INTER_CUBIC, borderMode=cv.BORDER_REPLICATE)
    cv.putText(rotated, "Angle: {:.2f} degrees".format(angle), (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

    # show the output image
    print("[INFO] angle: {:.2f}".format(angle))
    cv.imshow("Input", image)
    cv.imshow("Rotated", rotated)
    cv.waitKey(0)


if __name__ == "__main__":
    main()