如何将BMP矢量化为单条开放路径而非闭合路径?
二值图像转开放路径SVG的问题与解决方案
我正在开展一个简单的图像处理项目,需将二值图像转换为类似Adobe Illustrator中钢笔工具绘制的开放路径。当前遇到的问题是导出的SVG为闭合路径对象,而非开放路径。
已执行步骤
- 输入二值图像
- 使用Scikit反转二值图像
- 使用Scikit对反转图像进行骨架化处理
- 转换为8位图像
- 导出为JPG格式
- 使用
pillow将JPG转为BMP - 使用
potrace将BMP转为SVG
程序1 - 二值化、反转、骨架化等处理
from skimage.morphology import skeletonize from skimage.util import invert from skimage import data import matplotlib.pyplot as plt import cv2 import numpy as np import svgwrite # Reading BINARY input & converting to greyscale image = cv2.imread("C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\input2.JPG", cv2.IMREAD_COLOR) greyscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Threshold the grayscale image to get a binary image _, binary_image = cv2.threshold(greyscale, 127, 255, cv2.THRESH_BINARY) # Invert binary image inversion = invert(binary_image) # "Skeletonization" skeleton = skeletonize(inversion) # Convert image to 8-bit skeleton_8bit = np.uint8(skeleton * 255) # Increase line thickness by dilating the image kernel = np.ones((3,3),np.uint8) dilated_skeleton = cv2.dilate(skeleton_8bit, kernel, iterations = 1) # Create a new SVG drawing dwg = svgwrite.Drawing("C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\svg_output1.svg", profile='full') # Iterate over the pixels in the dilated skeleton image for y in range(skeleton_8bit.shape[0]): for x in range(skeleton_8bit.shape[1]): # If the pixel is white, add a line to the SVG if skeleton_8bit[y, x] > 0: dwg.add(dwg.line((x, y), (x+1, y), stroke=svgwrite.rgb(0, 0, 0, '%'))) # Save the SVG dwg.save() # Writing the image to a file cv2.imwrite("C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\skeleton_output1.JPG", skeleton_8bit)
程序2 - JPG转BMP
from PIL import Image # Open the JPG image image = Image.open('C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\output7.JPG') # Save the image as a BMP file image.save('C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\bitmap_output1.bmp')
程序3 - BMP转SVG
import subprocess # Define the Potrace command as a list of strings command = ["potrace", "-s", "-o", "C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\vectorized_output1.svg", "C:\\Users\\jackc\\OneDrive\\Desktop\\medial_skeleton\\bitmap_output1.bmp"] # Run the command subprocess.run(command, check=True)
问题细节
- 输入图像:一张手写风格的二值线条图
- 当前问题:导出的SVG并非由控制点构成的单条路径,而是由多个闭合路径组成的对象
- 预期结果:生成由单排控制点构成的单条开放路径,效果类似Adobe Illustrator“线条图”图像描摹功能处理二值图像的结果
解决方案更新
更新:已通过AutoTrace库的中心线功能实现需求,该库可从图像中提取中心线并生成符合预期的开放路径SVG
内容的提问来源于stack exchange,提问作者jackcbowers
相关产品推荐
相关产品推荐

