标签: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)
变换后的图片如下图所示
在Pycharm中用OpenCV的imutils模块矫正图片
标签:pen pre 最大 break col pictures 仿射变换 play bre
原文地址:https://www.cnblogs.com/yangyue-kai/p/11639301.html