使用OpenCV繪製帶有形心的三角形
形心也稱為幾何中心;它被定義為物體的中心點。而三角形的形心定義為三角形所有三條中線的交點。
計算三角形的形心
讓我們考慮一個ABC三角形,三角形的三個頂點是A(x1, y1)、B(x2, y2)和C(x3, y3)。那麼,三角形的形心可以透過取所有三個頂點的x和y座標的平均值來計算。
centroid of a triangle = ((x1+x2+x3)/3 , (y1+y2+y3)/3 )
在本文中,我們將看到使用OpenCV庫繪製帶有形心的三角形的Python程式。
使用預定義座標
在這種方法中,將使用預定義的座標繪製三角形。在這裡,我們將使用drawContours()方法連線座標點。
drawContours()方法用於連線邊界點以建立任何型別的形狀。以下是此函式的語法:
drawContours(img, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])
引數
img:目標影像。
contours:所有輸入輪廓。應作為Python列表傳遞。
contourIdx:指定輪廓的索引(在繪製單個輪廓時很有用)。如果為-1,則繪製所有輪廓。
其餘引數為顏色、粗細、線型等。
示例
在此示例中,將使用預定義的座標繪製三角形。
import cv2 import numpy as np image = np.ones((300, 300, 3), np.uint8) * 255 pt1 = (150, 100) pt2 = (100, 200) pt3 = (200, 200) triangle_cnt = np.array([pt1, pt2, pt3]) cv2.drawContours(image, [triangle_cnt], 0, (0,255,0), -1) # finding centroid centroid = ((pt1[0]+pt2[0]+pt3[0])//3, (pt1[1]+pt2[1]+pt3[1])//3) cv2.circle(image, centroid, 2, (0, 0, 255), 2) cv2.imshow("image", image) cv2.waitKey(0)
輸出
使用滑鼠拖動
要繪製帶有形心的三角形,我們將使用setMouseCallback()、cv.line()和cv2.circle()函式以及cv2.EVENT_LBUTTONDOWN滑鼠事件型別。
setMouseCallback()函式:它用於指定必須為特定視窗呼叫哪個函式。換句話說,該函式為指定的視窗建立一個滑鼠事件處理程式。
cv2.line():在影像中繪製連線點pt1和pt2之間的線。
cv2.circle():繪製給定中心和半徑的圓。
cv2.EVENT_LBUTTONDOWN:表示按下滑鼠左鍵。
示例
最初,使用**namedWindow()**方法將滑鼠回撥函式設定為視窗,以讀取使用者繪製三角形的座標。透過使用滑鼠點選事件,我們將識別x和y座標,然後使用cv2.line()函式繪製三角形。最後,將使用基本公式計算形心,並使用cv2.circle()函式繪製。
import numpy as np import cv2 as cv ix,iy,sx,sy = -1,-1,-1,-1 x_points = [] y_points = [] # mouse callback function def draw_lines(event, x, y, flags, param): global ix,iy,sx,sy # if the left mouse button was clicked, record the starting if event == cv.EVENT_LBUTTONDOWN: # draw circlar points of 2px cv.circle(img, (x, y), 3, (0, 0, 127), -1) if ix != -1: cv.line(img, (ix, iy), (x, y), (0, 0, 127), 2, cv.LINE_AA) x_points.append(x) y_points.append(y) else: sx, sy = x, y ix,iy = x, y if len(x_points) == 3: centroid = (sum(x_points)//3, sum(y_points)//3) cv2.circle(img, centroid, 2, (0, 0, 255), 2) return None # read image img = cv.resize(cv.imread("Images/Blank_img.png"), (1280, 720)) cv.namedWindow('image') cv.setMouseCallback('image',draw_lines) while(1): cv.imshow('image',img) if cv.waitKey(20) & 0xFF == ord('q'): break cv.destroyAllWindows()
輸出
在本文中,我們已經看到了使用Python中的OpenCV庫繪製帶有形心的三角形的兩種不同方法。