码迷,mamicode.com
首页 > 其他好文 > 详细

在Pycharm中用OpenCV的imutils模块矫正图片

时间:2019-10-09 09:36:17      阅读:491      评论:0      收藏:0      [点我收藏+]

标签:pen   pre   最大   break   col   pictures   仿射变换   play   bre   

在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

技术图片

变换后的图片如下图所示

技术图片

 

在Pycharm中用OpenCV的imutils模块矫正图片

标签:pen   pre   最大   break   col   pictures   仿射变换   play   bre   

原文地址:https://www.cnblogs.com/yangyue-kai/p/11639301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!