프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / DTI_PID / potrace.py @ 1ed39474

이력 | 보기 | 이력해설 | 다운로드 (3.66 KB)

1
#!/usr/bin/env/python3
2
# coding: utf-8
3

    
4
import re
5
import numpy as np, cv2, subprocess
6
import os, sys
7
from xml.dom import minidom
8
import svg.path
9
from xml.etree.ElementTree import Element, SubElement, dump, ElementTree
10
import xml.etree.ElementTree as ET
11
import SymbolBase
12
from shapely.geometry import LineString
13
from shapely.ops import linemerge
14
from LineDetector import LineDetector
15

    
16
# potrace command
17
POTRACE = os.path.dirname(os.path.realpath(__file__)) + '\\potrace.exe'
18
ADJUST = 10
19

    
20
def convertImageToSvg(imgFilePath, destFilePath, normalColor, hoverColor):
21
    thresh = 127
22

    
23
    image  = cv2.imread(imgFilePath, cv2.IMREAD_GRAYSCALE)
24
    threshold = cv2.threshold(image, thresh, 255, cv2.THRESH_BINARY)[1]
25

    
26
    # convert to bmp binary so that potrace can handle it
27
    retval, buf = cv2.imencode('.bmp', threshold)
28
    if retval == False:
29
        raise ValueError('Failed to convert into BMP binary data')
30
    # convert buf from numpy.ndarray to bytes
31
    binbmp = buf.tobytes()
32
    
33
    args = [
34
        POTRACE,
35
        '-', '-o-', '--svg'
36
    ]
37
    
38
    CREATE_NO_WINDOW = 0x08000000
39

    
40
    p = subprocess.Popen(
41
        args,
42
        stdin=subprocess.PIPE,
43
        stdout=subprocess.PIPE,
44
        stderr=subprocess.PIPE,
45
        creationflags=CREATE_NO_WINDOW
46
    )
47
        
48
    stdout, stderr = p.communicate(input=binbmp)
49
    if len(stderr) != 0:
50
        raise RuntimeError('Potrace threw error:\n' + stderr.decode('utf-8'))
51
    
52
    svgFile = open(destFilePath, "w")
53
    svgFile.write(stdout.decode("utf-8"))
54
    svgFile.close()
55

    
56
    ''' add lineargradient nodes to svg file '''
57
    try:
58
        doc = ET.parse(destFilePath)
59
        svg = doc.getroot()
60
        matches = [child for child in svg.getchildren() if re.search(re.compile('^\{.+\}g$'), child.tag)]
61
        if matches:
62
            matches[0].attrib['fill'] = 'url(#normal)'
63
            matches[0].attrib['stroke'] = 'url(#normal)'
64

    
65
            pathes = [child for child in matches[0].getchildren() if re.search(re.compile('^\{.+\}path$'), child.tag)]
66
            for path in pathes:
67
                path.attrib['stroke-width'] = '50'
68

    
69
        defs = Element('defs')
70
        gradient = ET.fromstring(normalColor)
71
        gradient.attrib['id'] = 'normal'
72
        defs.append(gradient)
73
        gradient = ET.fromstring(hoverColor)
74
        gradient.attrib['id'] = 'hover'
75
        defs.append(gradient)
76
        svg.append(defs)
77
        
78
        ''' remove ns0 from xml '''
79
        svgFile = open(destFilePath, 'w')
80
        svgFile.write(ET.tostring(svg, encoding='utf-8').decode('utf-8').replace('ns0:', '').replace(':ns0', ''))
81
        svgFile.close()
82
    except Exception as ex:
83
        from App import App
84
        from AppDocData import MessageType
85

    
86
        message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
87
        App.mainWnd().addMessage.emit(MessageType.Error, message)
88

    
89
if __name__ == '__main__':
90
    execpath = os.path.dirname(os.path.realpath(__file__))
91

    
92
    path = execpath + '\\res\\UY1-K-2007_P1_300dpi_black.png'
93
    #lines = linedraw.sketch(path)
94
    #linedraw.visualize(lines)
95
#    path = sys.argv[1]  # 1 argument given is a string for the path of drawing
96
    #imgLines = passpotrace(path)    #execpath + '\\res\\UY1-K-2007_P1_300dpi_black.png')
97
    image  = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
98
    lineDetector = LineDetector(image)
99
    lineDetector.Detect()
100
    
101
    try:
102
        xmlFilePath = os.path.dirname(path) + '\\' + os.path.basename(path).split('.')[0] + '.xml'
103
        file = open(xmlFilePath, 'w')
104
        for line in imgLines:
105
            file.write(str(line) + '\n')
106
        file.close()
107
    except Exception as ex:
108
        print('에러가 발생했습니다.\n', ex)
클립보드 이미지 추가 (최대 크기: 500 MB)