【发布时间】:2020-12-02 17:41:57
【问题描述】:
场景
我正在尝试在 Windows 10 设备上的 Anaconda 4.8.3 中的 Python 3.6 中将彩色 example.svg 文件转换为灰度 example_gs.svg。
尝试
首先,我尝试应用正则表达式将 'rgb(xxx,yyy,zzz)' 转换为黑色,但这会创建一个黑色矩形,在此过程中会丢失图像。接下来,我安装了 inkscape 并运行了一个灰度命令,该命令似乎可以正常工作,但没有修改 example.svg。使用枕头图像的第三次尝试未加载.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 文件更改为灰度图像?
【问题讨论】:
标签: python svg anaconda grayscale