hytos / DTI_PID / DTI_PID / potrace.py @ 8a48a60b
이력 | 보기 | 이력해설 | 다운로드 (3.4 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 |
defs = Element('defs')
|
64 |
gradient = ET.fromstring(normalColor) |
65 |
gradient.attrib['id'] = 'normal' |
66 |
defs.append(gradient) |
67 |
gradient = ET.fromstring(hoverColor) |
68 |
gradient.attrib['id'] = 'hover' |
69 |
defs.append(gradient) |
70 |
svg.append(defs) |
71 |
|
72 |
''' remove ns0 from xml '''
|
73 |
svgFile = open(destFilePath, 'w') |
74 |
svgFile.write(ET.tostring(svg, encoding='utf-8').decode('utf-8').replace('ns0:', '').replace(':ns0', '')) |
75 |
svgFile.close() |
76 |
except Exception as ex: |
77 |
from App import App |
78 |
from AppDocData import MessageType |
79 | |
80 |
message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno) |
81 |
App.mainWnd().addMessage.emit(MessageType.Error, message) |
82 | |
83 |
if __name__ == '__main__': |
84 |
execpath = os.path.dirname(os.path.realpath(__file__)) |
85 | |
86 |
path = execpath + '\\res\\UY1-K-2007_P1_300dpi_black.png'
|
87 |
#lines = linedraw.sketch(path)
|
88 |
#linedraw.visualize(lines)
|
89 |
# path = sys.argv[1] # 1 argument given is a string for the path of drawing
|
90 |
#imgLines = passpotrace(path) #execpath + '\\res\\UY1-K-2007_P1_300dpi_black.png')
|
91 |
image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) |
92 |
lineDetector = LineDetector(image) |
93 |
lineDetector.Detect() |
94 |
|
95 |
try:
|
96 |
xmlFilePath = os.path.dirname(path) + '\\' + os.path.basename(path).split('.')[0] + '.xml' |
97 |
file = open(xmlFilePath, 'w') |
98 |
for line in imgLines: |
99 |
file.write(str(line) + '\n') |
100 |
file.close()
|
101 |
except Exception as ex: |
102 |
print('에러가 발생했습니다.\n', ex)
|