在Pycharm中用OpenCV的imutils模塊矯正圖片


在OpenCV中有一個imutils模塊在圖形變換中非常方便,下面就是用該模塊對圖片進行仿射變換的代碼。

 1 from imutils import perspective
 2 from skimage.filters import threshold_local
 3 import cv2
 4 import imutils
 5 # 邊緣掃描
 6 image = cv2.imread("C:\\Users\\lenovo\\Pictures\\t1.png")
 7 ratio = image.shape[0] / 500.0# 比例
 8 orig = image.copy()
 9 image = imutils.resize(image, height = 500)
10 # 灰度轉換及邊緣查找
11 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
12 gray = cv2.GaussianBlur(gray, (5, 5), 0)
13 edged = cv2.Canny(gray, 75, 200)                          # 邊緣檢測
14 # 只保留輪廓
15 cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)#通過邊緣圖像找到輪廓
16 cnts = cnts[0] if imutils.is_cv2() else cnts[1]
17 # 用以區分OpenCV2.4和OpenCV3
18 cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # 保留最大輪廓
19 for c in cnts:
20     peri = cv2.arcLength(c, True)
21     approx = cv2.approxPolyDP(c, 0.02 * peri, True)            # 輪廓點
22     if len(approx) == 4:                                       # 表明找到四個輪廓點
23         screenCnt = approx
24         break
25 # 轉為鳥瞰圖
26 warped = perspective.four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
27 warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)              # 灰度轉換
28 T = threshold_local(warped, 11, offset = 10, method = "gaussian")
29 warped = (warped > T).astype("uint8") * 255
30 cv2.imshow("Original", imutils.resize(orig, height = 650))
31 cv2.imshow("Scanned", imutils.resize(warped, height = 650))
32 cv2.waitKey(0)
View Code

變換后的圖片如下圖所示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM