opencv實現圖像校正
本文實例為大傢分享瞭opencv實現圖像校正的具體代碼,供大傢參考,具體內容如下
1.引言:python實現傾斜圖像校正操作
2.思路流程:
(1)讀入,灰度化;
(2)高斯模糊;
(3)二值化圖像;
(4)閉開操作;
(5)獲取圖像頂點;
(6)旋轉校正
3.實現代碼:
import cv2 import numpy as np import imutils import time def Img_Outline(img_path): original_img = cv2.imread(img_path) gray_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray_img, (9, 9), 0) # 高斯模糊去噪(設定卷積核大小影響效果) _, RedThresh = cv2.threshold(blurred, 165, 255, cv2.THRESH_BINARY) # 設定閾值165(閾值影響開閉運算效果) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # 定義矩形結構元素 closed = cv2.morphologyEx(RedThresh, cv2.MORPH_CLOSE, kernel) # 閉運算(鏈接塊) opened = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel) # 開運算(去噪點) return original_img, opened def findContours_img(original_img, opened): contours = cv2.findContours(opened, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(contours) # print(cnts) # c = sorted(cnts, key=cv2.contourArea, reverse=True)[0] # 計算最大輪廓的旋轉包圍盒 c = max(cnts, key=cv2.contourArea) rect = cv2.minAreaRect(c) # print(rect) angle = rect[2] # rect[2] 返回的是矩形的旋轉角度 print("angle", angle) if angle == 90.0: return original_img, original_img else: box = np.int0(cv2.boxPoints(rect)) draw_img = cv2.drawContours(original_img.copy(), [box], -1, (0, 0, 255), 3) rows, cols = original_img.shape[:2] M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1) result_img = cv2.warpAffine(original_img, M, (cols, rows)) return result_img,draw_img if __name__ == "__main__": img_path = './result.jpg' start_time = time.time() original_img, opened = Img_Outline(img_path) result_img,draw_img = findContours_img(original_img,opened) print('消耗的時間為:',(time.time() - start_time)) cv2.imshow("original_img", original_img) cv2.imshow("draw_img", draw_img) cv2.imshow("result_img", result_img) cv2.waitKey(0) cv2.destroyAllWindows()
4.效果展示:
原圖
標框出圖
旋轉後的圖
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。