文档扫描仪的构建——使用Python,OpenCV应用透视变换来获得图像的自顶向下的“鸟瞰图”
生活随笔
收集整理的這篇文章主要介紹了
文档扫描仪的构建——使用Python,OpenCV应用透视变换来获得图像的自顶向下的“鸟瞰图”
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用Python,OpenCV應(yīng)用透視變換來獲得圖像的自頂向下的“鳥瞰圖”
- 1. 效果圖
- 2. 應(yīng)用透視變換的步驟
- 3. 優(yōu)化:矩形角點的獲取
- 4. 源碼
- 參考
這篇博客演示了如何使用4點OpenCV getPerspectiveTransform來構(gòu)建一個文檔掃描儀應(yīng)用程序!
1. 效果圖
左圖是原圖,右圖是應(yīng)用透視變換得到的自頂向下的“鳥瞰圖”
同樣的“鳥瞰圖”
橙色是最小外接矩形 boundingRect結(jié)果
綠色是面積最小外接矩形 minAreaRect的結(jié)果
紅色是輪廓近似的結(jié)果
2. 應(yīng)用透視變換的步驟
- 輪廓檢測獲取左圖中矩形框的四個角點
- 對四個角點按(左上、右上、左下、右下進行排序)
- 確定新圖像的寬度與高度;
- 獲取轉(zhuǎn)換矩陣;
- 應(yīng)用透視變換獲得“鳥瞰圖”;
3. 優(yōu)化:矩形角點的獲取
通過了findContours,輪廓檢測來近似獲取角點;
圖中是矩形,因此用進來輪廓后4個點來進行判斷;其他的 如三角形、圓形、正方形、多邊形等的檢測可以參考我之前的博客;
4. 源碼
# USAGE
# python transform_example.py --image images/example_01.png --coords "[(73, 239), (356, 117), (475, 265), (187, 443)]"# 導(dǎo)入必要的包
import argparse
import sysimport cv2
import imutils
import numpy as np
from imutils.perspective import four_point_transform# 構(gòu)建命令行參數(shù)及解析
# --image 原始圖像路徑
# 四點的坐標(biāo),ROI圖像區(qū)域
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", default='images/example_01.png', help="path to the image file")
ap.add_argument("-c", "--coords", default='[(73, 239), (356, 117), (475, 265), (187, 443)]',help="comma seperated list of source points")
args = vars(ap.parse_args())# 加載圖像 并獲取其坐標(biāo)List
image = cv2.imread(args["image"])pts = np.array(eval(args["coords"]), dtype="float32")
print(type(pts))
print(pts)def getROI(image):gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)blurred = cv2.GaussianBlur(gray, (5, 5), 0)edged = cv2.Canny(blurred, 75, 200)# 應(yīng)用輪廓檢測獲取輪廓cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)if cnts is not None:# 外接矩形(x, y, w, h) = cv2.boundingRect(cnts[0])peri = cv2.arcLength(cnts[0], True)approx = cv2.approxPolyDP(cnts[0], 0.04 * peri, True)cv2.rectangle(image, (x - 5, y - 5), (x + w, y + h), (0, 128, 255), 0)# 面積最小外接矩形box = cv2.minAreaRect(cnts[0])box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)box = np.array(box, dtype="int")cv2.drawContours(image, [box], -1, (0, 255, 0), 2)# 展示輸出圖像# cv2.imshow("output", image)# cv2.waitKey(0)# 輪廓是由一系列頂點組成的;如果是三角形,將擁有3個向量. 如果是正方形/矩形則具有4個向量,如果是正方形,則寬高比在0.95~1.05之間if len(approx) == 4:print('rectangele')a = np.reshape(approx, (4, 2))for i in a:print(i)x = i[0]y = i[1]cv2.circle(image, (x, y), 8, (0, 0, 255), -1)return areturn Nonepts = getROI(image)
if pts is None:print("pts is None...")sys.exit()print(pts)# 應(yīng)用點變換以獲取鳥瞰視圖
warped = four_point_transform(image, pts)# 展示原始及變換后的圖像
cv2.imshow("Original", image)
cv2.imshow("Warped", warped)
cv2.waitKey(0)
參考
- https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
總結(jié)
以上是生活随笔為你收集整理的文档扫描仪的构建——使用Python,OpenCV应用透视变换来获得图像的自顶向下的“鸟瞰图”的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3 pathlib让编程更美
- 下一篇: 使用Python,OpenCV实现图像之