场景
我正在尝试在 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 设备上使用 Python 3.6 将彩色的 .svg
文件转换为灰度图像?