本項目為python項目需要安裝python及python的opencv模塊:opencv_python-4.0.1-cp37-cp37m-win32.whl 和 python的矩陣運算模塊:numpy。
1、第一步,安裝python3.7,具體安裝步驟略。
2、第二步,使用pip安裝python的矩陣運算模塊:numpy。
python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
3,第三步,使用pip安裝python的opencv模塊:opencv_python。
(1) 先去官網https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv,下載相應Python版本的OpenCV的whl文件,如本人下載的opencv_python‑3.4.1‑cp36‑cp36m‑win_amd64.whl(此文件已經下載並在項目壓縮包里)
(2) 將下載的whl文件放入python的\Lib\site-packages文件夾,我文件路徑為:C:\Users\pangguoming\AppData\Local\Programs\Python\Python37-32\Lib\site-packages
(3) 用pip安裝此文件
pip install opencv_python-4.0.1-cp37-cp37m-win32.whl
4、第四步,運行python腳本imgtxtcorr.py ,此腳本將讀取當前目錄下的1.jpg文件進行校正,並打開校正后的圖片。
# -*- coding: UTF-8 -*- import numpy as np import cv2 ## 圖片旋轉 def rotate_bound(image, angle): #獲取寬高 (h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) # 提取旋轉矩陣 sin cos M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) # 計算圖像的新邊界尺寸 nW = int((h * sin) + (w * cos)) # nH = int((h * cos) + (w * sin)) nH = h # 調整旋轉矩陣 M[0, 2] += (nW / 2) - cX M[1, 2] += (nH / 2) - cY return cv2.warpAffine(image, M, (nW, nH),flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) ## 獲取圖片旋轉角度 def get_minAreaRect(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.bitwise_not(gray) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] coords = np.column_stack(np.where(thresh > 0)) return cv2.minAreaRect(coords) image_path = "54321.png" image = cv2.imread(image_path) angle = get_minAreaRect(image)[-1] rotated = rotate_bound(image, angle) cv2.putText(rotated, "angle: {:.2f} ".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("imput", image) cv2.imshow("output", rotated) cv2.waitKey(0)
可矯正所有 圖片格式包括 png jpg tif等