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库展示了两种不同的方法来绘制带有质心的三角形。