溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用Python?OpenCV尋找兩條曲線直接的最短距離

發(fā)布時間:2022-02-08 10:38:31 來源:億速云 閱讀:287 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了怎么用Python OpenCV尋找兩條曲線直接的最短距離的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇怎么用Python OpenCV尋找兩條曲線直接的最短距離文章都會有所收獲,下面我們一起來看看吧。

import numpy as np
import math
import cv2

def cal_pt_distance(pt1, pt2):
  dist = math.sqrt(pow(pt1[0]-pt2[0],2) + pow(pt1[1]-pt2[1],2))
  return dist

font = cv2.FONT_HERSHEY_SIMPLEX
img = cv2.imread('01.png')
#cv2.imshow('src',img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (3,3), 0)

ret,thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
image,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#thresh,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

flag = False
minDist = 10000
minPt0 = (0,0)
minPt1 = (0,0)
for i in range(0,len(contours[1])):#遍歷所有輪廓
  pt = tuple(contours[1][i][0])
  #print(pt)
  min_dis = 10000
  min_pt = (0,0)
  #distance = cv2.pointPolygonTest(contours[1], pt, False)
  for j in range(0,len(contours[0])):
    pt2 = tuple(contours[0][j][0])
    distance = cal_pt_distance(pt, pt2)
    #print(distance)
    if distance < min_dis:
      min_dis = distance
      min_pt = pt2
      min_point = pt
  if min_dis < minDist:
    minDist = min_dis
    minPt0 = min_point
    minPt1 = min_pt
  temp = img.copy()
  cv2.drawContours(img,contours,1,(255,255,0),1)
  cv2.line(temp,pt,min_pt,(0,255,0),2,cv2.LINE_AA)
  cv2.circle(temp, pt,5,(255,0,255),-1, cv2.LINE_AA)
  cv2.circle(temp, min_pt,5,(0,255,255),-1, cv2.LINE_AA)
  cv2.imshow("img",temp)
  if cv2.waitKey(1)&0xFF ==27: #按下Esc鍵退出
    flag = True
    break
  if flag:
    break

cv2.line(img,minPt0,minPt1,(0,255,0),2,cv2.LINE_AA)
cv2.circle(img, minPt0,3,(255,0,255),-1, cv2.LINE_AA)
cv2.circle(img, minPt1,3,(0,255,255),-1, cv2.LINE_AA)
cv2.putText(img,("min_dist=%0.2f"%minDist), (minPt1[0],minPt1[1]+15), font, 0.7, (0,255,0), 2)

cv2.imshow('result', img)
cv2.imwrite('result.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

原圖:

怎么用Python?OpenCV尋找兩條曲線直接的最短距離

結(jié)果圖:

怎么用Python?OpenCV尋找兩條曲線直接的最短距離

關(guān)于“怎么用Python OpenCV尋找兩條曲線直接的最短距離”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“怎么用Python OpenCV尋找兩條曲線直接的最短距離”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI