参考链接:http://yuncode.net/code/c_5acf1045152e662
最近需要生成一批含有箭头的样本,cv2自带的画箭头的函数和微信截图中画箭头的形状不一样,因此需要重新写一个生成微信箭头的函数(如果cv2有,请告诉我一下)
*** 可以观察到两者的主要差异体现在 尾部和箭头
利用python+cv2生成:(可自己调整一些随机元素,颜色,起止位置等)
主要过程: 根据夹角求出三角形顶点的坐标
def drow_arrow_test(img):
color=(127,34,175)
start_x = 10
start_y = 20
stop_x = 100
stop_y = 100
len = math.sqrt(math.pow(stop_x-start_x,2)+math.pow(stop_y-start_y,2))
#开始是 直线与x轴的夹角
w = stop_x-start_x
h = stop_y-start_y
k = math.atan(h/w) #原始直线与x轴的夹角
siny = math.sin(k)
cosy = math.cos(k)
# par = 5 三角形的高 等腰三角形 底边=par
par = 20
len_no_act = len-par
len_par = math.sqrt(math.pow(len_no_act,2)+math.pow(par/2,2))
k2 = math.atan((par/2)/len_no_act) # 箭头与起始点与终点的夹角
left_k = k-k2
left_siny = math.sin(left_k)
left_cosy = math.cos(left_k)
left_y = int(left_siny*len_par + start_y)
left_x = int(left_cosy*len_par + start_x)
# 中点坐标
mid_x = int(cosy*len_no_act+start_x)
mid_y = int(siny*len_no_act+start_y)
# left 关于中点的对称点坐标 right
right_x = int(2*mid_x-left_x)
right_y = int(2*mid_y-left_y)
# 箭头的中点
left_x2 = int((mid_x+left_x)/2)
left_y2 = int((mid_y + left_y)/2)
right_x2 = int((mid_x+right_x)/2)
right_y2 = int((mid_y + right_y)/2)
# 画直线
cv2.line(img, (start_x, start_y), (left_x2, left_y2), color, 1)
cv2.line(img, (start_x, start_y), (right_x2, right_y2), color, 1)
cv2.line(img, (left_x, left_y), (stop_x,stop_y), color, 1)
cv2.line(img, (right_x, right_y), (stop_x,stop_y), color, 1)
cv2.line(img, (right_x, right_y), (left_x, left_y), color, 1)
cv2.line(img, (start_x, start_y), (mid_x, mid_y), color, 1)
#填充
triangle1 = np.array([[start_x,start_y],[left_x2, left_y2],[right_x2, right_y2]])
triangle2 = np.array([[left_x, left_y], [right_x, right_y],[stop_x,stop_y]])
cv2.fillPoly(img, [triangle1, triangle2], color)
cv2.imwrite( '_arrow_other' + str(1) + '.jpg', img)
plt.imshow(img)
plt.show()
效果: