我正在使用Python的openCV从图像中提取轮廓。现在我需要将这些轮廓路径(列表)导出为SVG路径。我该如何实现?
代码:
ret,thresh = cv2.threshold(imgray,27,25,0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_TC89_L1)
print(type(contours)) #type list
问题已经以下方式解决:
c = max(contours, key=cv2.contourArea) #max contour
f = open('path.svg', 'w+')
f.write('<svg width="'+str(width)+'" height="'+str(height)+'" xmlns="http://www.w3.org/2000/svg">')
f.write('<path d="M')
for i in xrange(len(c)):
#print(c[i][0])
x, y = c[i][0]
print(x)
f.write(str(x)+ ' ' + str(y)+' ')
f.write('"/>')
f.write('</svg>')
f.close()
potrace
进行平滑处理... http://potrace.sourceforge.net - Mark Setchellpotrace
将其转换为平滑的SVG文件。 - Mark Setchellwith open("path.svg", "w+") as f:
f.write(f'<svg width="{w}" height="{h}" xmlns="http://www.w3.org/2000/svg">')
for c in contours:
f.write('<path d="M')
for i in range(len(c)):
x, y = c[i][0]
f.write(f"{x} {y} ")
f.write('" style="stroke:pink"/>')
f.write("</svg>")
path
语句,然后将它们写入文本文件 https://www.w3schools.com/graphics/svg_path.asp。你可能需要进行初始遍历以确定页面大小的最大尺寸,或者你可以使用找到轮廓的原始图像的尺寸。 - Mark Setchell