在 python 中将 SVG 转换为灰度

Convert an SVG to grayscale in python

场景

我正在尝试在 Windows 10 设备上的 Anaconda 4.8.3 中的 python 3.6 中将彩色 example.svg 文件转换为灰度 example_gs.svg

尝试次数

首先,我尝试应用正则表达式将 'rgb(xxx,yyy,zzz)' 转换为黑色,但创建了一个黑色矩形,在此过程中丢失了图像。接下来我安装了 inkscape 和 运行 一个灰度命令,它似乎可以工作但没有修改 example.svg。第三次尝试 pillow Image 没有加载 .svg.

MWE

# conda install -c conda-forge inkscape
# https://www.commandlinefu.com/commands/view/2009/convert-a-svg-file-to-grayscale
# inkscape -f file.svg --verb=org.inkscape.color.grayscale --verb=FileSave --verb=FileClose
import re
import os
import fileinput
from PIL import Image
import cv2

# Doesn't work, creates a black square. Perhaps set a threshold to not convert rgb white/bright colors
def convert_svg_to_grayscale(filepath):
    # Read in the file
    with open(filepath, 'r') as file :
      filedata = file.read()

    # Replace the target string
    filedata = re.sub(r'rgb\(.*\)', 'black', filedata)

    # Write the file out again
    with open(filepath, 'w') as file:
      file.write(filedata)
    
# opens inkscape, converts to grayscale but does not actually export to the output file again
def convert_svg_to_grayscale_inkscape(filepath):
   command = f'inkscape -f {filepath} --verb=org.inkscape.color.grayscale --verb=FileSave --verb=FileClose'
   os.system(f'cmd /k {command}')
   
# Pillow Image is not able to import .svg files
def grayscale(filepath):
    image = Image.open(filepath)
    cv2.imwrite(f'{filepath}', image.convert('L'))


# walks through png files and calls function to convert the png file to .svg
def main():
    filepath = 'example.svg'            
    convert_svg_to_grayscale_inkscape(filepath)
    convert_svg_to_grayscale(filepath)
    grayscale(filepath)
                

if __name__ == '__main__':
    main()

问题

如何在 windows 设备上将彩色 .svg 文件更改为 python 3.6 中的灰度图像?

您选择了正确的灰度转换工具。您的最后一次尝试很好,但您需要导入提供 svg2png 功能的 cairosvg。然后,使用 Pillow 加载 png 文件并将其转换为 np.array,然后您可以轻松地使用 openCV 加载它并将其转换为灰度,就像您所做的那样。最后你可以使用 svglib 和 reportlab 导出 svg 中的图像。 使用此代码段作为示例: