问题背景
使用OpenCV-Python处理图像时,有函数cv.line()函数可以快速画出直线,本以为使用该函数修改参数可以快速画出虚线等特殊直线,查阅OpenCV文档可以看到,cv.line()函数有参数lineType。那么该参数是修改所画直线类型的么?进一步查阅文档后发现lineType有以下四个值:
- cv.FILLED
- cv.LINE_4
- cv.LINE_8
- cv.LINE_AA
官方文档cv.line()描述这么描述该函数
The function line draws the line segment between pt1 and pt2 points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased lines are drawn using Gaussian filtering.
由此看出这里的lineType参数并不是所需的虚线、实线这个'Type'的意思。查询资料后发现似乎没法直接使用OpenCV的函数画虚线,因此需要自己实现画虚线的功能。
绘制虚线函数
import cv2
import numpy as np
def drawline(img,pt1,pt2,color,thickness=1,style='dotted',gap=20):
dist =((pt1[0]-pt2[0])**2+(pt1[1]-pt2[1])**2)**.5
pts= []
for i in np.arange(0,dist,gap):
r=i/dist
x=int((pt1[0]*(1-r)+pt2[0]*r)+.5)
y=int((pt1[1]*(1-r)+pt2[1]*r)+.5)
p = (x,y)
pts.append(p)
if style=='dotted':
for p in pts:
cv2.circle(img,p,thickness,color,-1)
else:
s=pts[0]
e=pts[0]
i=0
for p in pts:
s=e
e=p
if i%2==1:
cv2.line(img,s,e,color,thickness)
i+=1
该函数实现通过调整gap参数调整画点间隔的方式变相实现了画虚线的功能。使用本函数画出的虚线明显看出由点组成,可以对其进行调整使用短线代替点。