Python OpenCV寻找两条曲线直接的最短距离
程序员文章站
2022-06-18 15:14:20
本文实例为大家分享了python opencv两条曲线直接最短距离的寻找方法,供大家参考,具体内容如下import numpy as npimport mathimport cv2def cal_pt...
本文实例为大家分享了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()
原图:
结果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 软文文案这样写走心又带货