# Author: Winter Liu is coming! import cv2 as cv import numpy as np import pytesseract

Def contour_demo(img): gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gray = cv.GaussianBlur(gray, (5, 5), 1) ref, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY) kernel = np.ones((9, 9), np.uint8) thresh = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=4) contours, hierachy = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) print(len(contours)) return contours

def capture(img): Contours = contour_demo(img) # Print (cv.arcLength(Contour,True)) img_copy = img.copy() # approxPolyDP Approx = CV. ApproxPolyDP (contour, 22, TRUE) # print(approx. Shape) # print(approx) # print(approx) # print(approx) # print(approx) # CV. DrawContours (img_copy, For x, y in zip(approx[:, 0, 0], approx[:, 0, 0], 0, 1]): approx[:, 0, 0] Array ([(0, 0), (0, 1500), (1000, 1500), (1000, 0)], p1 = np.array(n, dType = NP.float32) Dtype = np. Float32) M = CV. GetPerspectiveTransform (p1, p2) # # transformation matrix using perspective transformation result = CV. WarpPerspective (img_copy, M, (0, Result = result[:1501, :1001] CV. Imwrite (r”C: PycharmProjects\OpenCV\ PIC \ OCR “, result) return result

# Image recognition code, you need to download and install the open source toolkit Pytesseract, # change “CMD” in “C:\Python\Python37\Lib\site-packages\pytesseract\pytesseract.py” to the absolute path def ocr_img(img): Gray = CV. CvtColor (img, CV.COLOR_BGR2GRAY) # print(text)


src = cv.imread(r”C:\PycharmProjects\OpenCV\pic\page.jpg”)

res = capture(src)

ocr_img(res)

cv.waitKey(0)

cv.destroyAllWindows()