【问题标题】:Convert an SVG to grayscale in python在python中将SVG转换为灰度
【发布时间】: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


    【解决方案1】:

    您选择了正确的灰度转换工具。您的最后一次尝试很好,但您需要导入提供 svg2png 功能的cairosvg。然后,使用 Pillow 加载 png 文件并将其转换为 np.array,然后您可以使用 openCV 轻松加载它并将其转换为灰度。最后,您可以使用 svglib 和 reportlab 将图像导出为 svg。 以这个 sn-p 为例: https://stackoverflow.com/a/62345450/13605264

    【讨论】:

    • 将矢量图像转换为 PNG 光栅图像,然后再转换回 SVG 矢量图像会丢失大量信息 - 如果它完全有效的话。
    • 您希望如何进行反向转换?从 svglib 文档来看,它无法将 PNG 作为输入,只有 SVG。
    • 这里是在python中转换png to svg的一个暗示。此外,我很乐意了解您的更好解决方案并从中学习。这只是我能想到的第一个解决方案
    • 您链接的代码会将光栅图像的每个像素转换为 1*1px 矩形。生成的图像虽然在技术上是矢量图像,但将失去其可扩展性:将其缩放 10 倍,您将看到的只是许多块。 - 我没有好的解决方案,我的评论是关于光栅和矢量图像之间的一般关系以及矢量到光栅转换always causes information loss 的数学事实。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2020-04-29
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多