我使用 opencv 在 Python 中检测轮廓。我通过搜索编写了将此轮廓保存为 dxf 文件的代码,如下所示。
cap = EasyPySpin.VideoCapture(0)
_, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
frame = cv2.resize(frame, dsize=(0,0), fx=0.26, fy=0.26, interpolation=cv2.INTER_AREA)
frame_blr = cv2.GaussianBlur(frame, (3, 3), 0)
canny = cv2.Canny(frame_blr, 255, 0)
contours, hierarchy=cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours_draw = cv2.drawContours(frame, contours, -1, (0, 255, 0), 1)
cv2.imshow('contour', contours_draw)
contours = [np.squeeze (cnt, axis = 1) for cnt in contours]
ctr = contours[1]
dwg = ezdxf.new ('R2010') # create a new DXF R2010 drawing, official DXF version name: 'AC1024'
msp = dwg.modelspace () # add new entities to the model space
dwg.layers.new (name = 'MyLines', dxfattribs = {'color': 3}) # 3 = Green
for i in range (len (ctr)):
n = i + 1
if n>= len (ctr):
n = 0
msp.add_line (ctr [i], ctr [n], dxfattribs = {'layer': 'MyLines'}) # add a LINE entity
print (ctr [i], '->', ctr [n])
dwg.saveas ('line.dxf')
但是检测到的轮廓和dxf文件中画的线是不一样的。此外,每次运行时,dxf 文件中都会绘制一条略有不同的线。我不知道为什么。
轮廓图像 >在此处输入图像描述 DXF 文件 >在此处输入图像描述
而且我不知道这段代码是什么意思。
contours = [np.squeeze (cnt, axis = 1) for cnt in contours]
ctr = contours[1]
如果我删除此代码并将 crt 编辑为轮廓,则会发生以下错误。
Traceback (most recent call last):
File "c:/Users/MyPc/KHS/p40.contour detection, (x,y).py", line 38, in <module>
msp.add_line (contours [i], contours [n], dxfattribs = {'layer': 'MyLines'}) # add a LINE entity
File "C:\Users\MyPc\AppData\Local\Programs\Python\Python38\lib\site-packages\ezdxf\graphicsfactory.py", line 121, in add_line
dxfattribs["start"] = Vec3(start)
File "src\ezdxf\acc\vector.pyx", line 417, in ezdxf.acc.vector.Vec3.__cinit__
TypeError: invalid argument count