pyhon+OpenCV中的快速直線檢測
pyhon+OpenCV中的快速直線檢測
資料來源: https://mp.weixin.qq.com/s?__biz=MjM5NTE3NjY5MA==&mid=2247484994&idx=2&sn=87f2e3a51b676869cf8fa304a66ee405&chksm=a6fdcfdf918a46c9fb3c2650f52eb0a9cba4ee774d9d67f1ff4c702c474cfb0fba6cec0e7000&scene=126&sessionid=1602570759&key=7674ee21d747fecf4d688b2265e9fd4d3e837e5865a5347d6a608bec91ddeb389beef52ec1c331beb1a06355f24523b2b92947eb0070be30fba359b9ed2d05df78292fdf1afb8b6ed386ffdd5b0eed163d94aebe4c433011a06a4b689294fc0559f8cb9c5559b419757877484a4703a1ba24bc02810a9338b65a60d84e658373&ascene=1&uin=MjIwODk2NDgxNw%3D%3D&devicetype=Windows+10+x64&version=6300002f&lang=zh_TW&exportkey=Al4BY6AoJqeuKxr5Rr8Erz8%3D&pass_ticket=t2NSb%2Bmc8NuxLUwFdAJLJl1KiHlj2yfEDRJjrQVKi3LX0NhUF%2FzRbYtuCFbskDVs&wx_header=0
cv::ximgproc::FastLineDetectors是opencv-contrib中用於檢測直線的模塊,該方法能夠在垂直方向獲得精度更高的直線檢測結果,並且不需要調節參數。該函數是LineSegmentDetector因版權問題從OpenCV中可移除後最易用的直線檢測小能手,沒有一個。此處介紹該功能的使用方法其輸出結果剖析。
環境
python3.6
opencv-contrib-python 4.4.0.44
[pip uninstall opencv-python]
[pip install opencv-contrib-python]
PS.在OpenCV 4.1.0之前的版本中,有一個LineSegmentDetector模塊,功能強大,檢測直線非常方便,但該函數因為版權問題已在4.1.X版本上已刪除,故此處不討論此方案。LineSegmentDetector相關的問題可以參考:
python的線段檢測器的任何實現
https://answers.opencv.org/question/215800/any-implementation-of-linesegmentdetector-for-python/
需要刪除LineSegmentDetector以獲得許可證
https://github.com/WPIRoboticsProjects/GRIP/issues/961
FastLineDetectors應用示例01
import cv2 import numpy as np img = cv2.imread('sudo.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #Create default Fast Line Detector (FSD) fld = cv2.ximgproc.createFastLineDetector() #Detect lines in the image lines = fld.detect(gray) #Draw detected lines in the image drawn_img = fld.drawSegments(gray,lines) cv2.imshow("FLD", drawn_img) cv2.waitKey(0)
FastLineDetectors應用示例02
import cv2 import numpy as np from scipy.spatial import distance as dist img = cv2.imread('sDQLM.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #Create default Fast Line Detector (FSD) fld = cv2.ximgproc.createFastLineDetector() #Detect lines in the image lines = fld.detect(gray) dMax = 0 bx_Max = 0 by_Max = 0 ex_Max = 0 ey_Max = 0 for L in lines: bx,by,ex,ey = L[0] # compute the Euclidean distance between the two points, D = dist.euclidean((bx, by), (ex, ey)) if D > dMax: dMax = D bx_Max = bx by_Max = by ex_Max = ex ey_Max = ey lineMax = np.array([[[bx_Max, by_Max, ex_Max,ey_Max]]]) #Draw detected lines in the image drawn_img = fld.drawSegments(gray,lineMax,True) cv2.circle(drawn_img, (bx_Max, by_Max), 1, (255,0,0), 2)#line begin cv2.circle(drawn_img, (ex_Max, ey_Max), 1, (0,255,0), 2)#line end cv2.imshow("FLD", drawn_img) cv2.waitKey(0)