상세 컨텐츠

본문 제목

Text Skew Correction

Coding/Image

by linguana 2021. 5. 7. 11:19

본문

Text skew correction with OpenCV and Python - PyImageSearch

 

Text skew correction with OpenCV and Python - PyImageSearch

Learn how to apply text skew correction to deskew text in images using Python and OpenCV.

www.pyimagesearch.com

2017년 2월 20일 포스팅


기울어진 글 똑바로 세워주기

수행 단계:

  • 이미지 내에 글자가 있는 구역 파악하기
  • 글자가 기울어져 있는 각도 계산하기
  • 똑바로 세우기 위해 글 회전시키기

일반적으로 "문서 자동 분석" 분야에서 활용됨. (물론 다른 분야에서 활용해도 O.K)


데이터셋

특정 각도로 기울어져 있는 문단 4개 이미지:

<그림 1> 기울어진 글자 데이터

(+ : 시계방향; - : 반시계방향)
좌측 상단 이미지: -4도; neg_4.png
우측 상단 이미지: -28도; neg_28.png
좌측 하단 이미지: +24도; pos_24.png
우측 하단 이미지: +41도; pos_41.png


correct_skew.py

  • 인자 파싱
  • 데이터 로드
  • 전처리 (그레이 스케일, threshold로 이진화)
# import the necessary packages
import numpy as np
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
	help="path to input image file")
args = vars(ap.parse_args())

# load the image from disk
image = cv2.imread(args["image"])

# convert the image to grayscale and flip the foreground
# and background to ensure foreground is now "white" and
# the background is "black"
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bitwise_not(gray)

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

<그림 2> threshold 수행하여 이진화된 이미지. 글자는 흰색, 배경은 검정색 됨.

본격적으로 각도 수정해주는 부분

# grab the (x, y) coordinates of all pixel values that
# are greater than zero, then use these coordinates to
# compute a rotated bounding box that contains all
# coordinates
coords = np.column_stack(np.where(thresh > 0))
angle = cv2.minAreaRect(coords)[-1]

# the `cv2.minAreaRect` function returns values in the
# range [-90, 0); as the rectangle rotates clockwise the
# returned angle trends to 0 -- in this special case we
# need to add 90 degrees to the angle
if angle < -45:
	angle = -(90 + angle)
    
# otherwise, just take the inverse of the angle to make
# it positive
else:
	angle = -angle
    
# rotate the image to deskew it
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h),
	flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    
# draw the correction angle on the image so we can validate it
cv2.putText(rotated, "Angle: {:.2f} degrees".format(angle),
	(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
    
# show the output image
print("[INFO] angle: {:.3f}".format(angle))
cv2.imshow("Input", image)
cv2.imshow("Rotated", rotated)
cv2.waitKey(0)

파일 실행하기

# ======================================================
$ python correct_skew.py --image images/neg_4.png 
[INFO] angle: -4.086

$ python correct_skew.py --image images/neg_28.png 
[INFO] angle: -28.009

$ python correct_skew.py --image images/pos_24.png 
[INFO] angle: 23.974

$ python correct_skew.py --image images/pos_41.png 
[INFO] angle: 41.037

'Coding > Image' 카테고리의 다른 글

HOG & SVM  (0) 2021.05.07
Histogram  (0) 2021.05.07
Object Detection Terminology Overview  (0) 2021.05.06
IoU (Intersection over Union)  (0) 2021.05.06
YOLO - PyImageSearch  (0) 2021.05.06

관련글 더보기