Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert contour paths to svg paths

I am using openCV with python to extract contours from an image. Now I need to export these contour paths (list) as an svg paths. How can I achieve this ?

code:

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
like image 829
Laxman Avatar asked Mar 30 '17 04:03

Laxman


2 Answers

the problem has been solved as follows:

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()
like image 74
Laxman Avatar answered Oct 17 '22 14:10

Laxman


The other answer only save the outmost contour in svg file, which is not my case. To save all the contours found by opencv, you could instead do this:

with 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>")
like image 38
ospider Avatar answered Oct 17 '22 16:10

ospider