프로젝트

일반

사용자정보

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

hytos / DTI_PID / DTI_PID / potrace.py @ c1cbaa3a

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

1 e3cdaf74 humkyung
#!/usr/bin/env/python3
2
# coding: utf-8
3
4 b52cccb4 humkyung
import re
5 e3cdaf74 humkyung
import numpy as np, cv2, subprocess
6 b0323751 humkyung
import os, sys
7 9dddbb7d humkyung
from xml.dom import minidom
8
import svg.path
9
from xml.etree.ElementTree import Element, SubElement, dump, ElementTree
10 b52cccb4 humkyung
import xml.etree.ElementTree as ET
11 9dddbb7d humkyung
import SymbolBase
12 b0323751 humkyung
from shapely.geometry import LineString
13
from shapely.ops import linemerge
14 5fd8cd99 humkyung
from LineDetector import LineDetector
15 e3cdaf74 humkyung
16
# potrace command
17
POTRACE = os.path.dirname(os.path.realpath(__file__)) + '\\potrace.exe'
18 e08fd87f 김정우
ADJUST = 10
19 9dddbb7d humkyung
20 b52cccb4 humkyung
def convertImageToSvg(imgFilePath, destFilePath, normalColor, hoverColor):
21 aaf53137 김정우
    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 1b502652 김정우
    retval, buf = cv2.imencode('.bmp', threshold)
28 aaf53137 김정우
    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 a393ab0e esham21
    CREATE_NO_WINDOW = 0x08000000
39
40 aaf53137 김정우
    p = subprocess.Popen(
41
        args,
42
        stdin=subprocess.PIPE,
43
        stdout=subprocess.PIPE,
44
        stderr=subprocess.PIPE,
45 a393ab0e esham21
        creationflags=CREATE_NO_WINDOW
46 35d6d96c 김정우
    )
47 aaf53137 김정우
        
48
    stdout, stderr = p.communicate(input=binbmp)
49
    if len(stderr) != 0:
50
        raise RuntimeError('Potrace threw error:\n' + stderr.decode('utf-8'))
51 35d6d96c 김정우
    
52 1b502652 김정우
    svgFile = open(destFilePath, "w")
53
    svgFile.write(stdout.decode("utf-8"))
54
    svgFile.close()
55 aaf53137 김정우
56 b52cccb4 humkyung
    ''' 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 ce1ae611 humkyung
            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 b52cccb4 humkyung
        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 8a48a60b humkyung
        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 b52cccb4 humkyung
89 cd198f3b humkyung
if __name__ == '__main__':
90
    execpath = os.path.dirname(os.path.realpath(__file__))
91 e3cdaf74 humkyung
92 cd198f3b humkyung
    path = execpath + '\\res\\UY1-K-2007_P1_300dpi_black.png'
93 5fd8cd99 humkyung
    #lines = linedraw.sketch(path)
94
    #linedraw.visualize(lines)
95 cd198f3b humkyung
#    path = sys.argv[1]  # 1 argument given is a string for the path of drawing
96 5fd8cd99 humkyung
    #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 b0323751 humkyung
    
101 5fd8cd99 humkyung
    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)