[英]Convert an SVG to grayscale in python
I'm trying to convert a colored example.svg
file into a grayscaled example_gs.svg
in python 3.6 in Anaconda 4.8.3 on a Windows 10 device.
首先,我嘗試應用正則表達式將 'rgb(xxx,yyy,zzz)' 轉換為黑色,但這會創建一個黑色矩形,在此過程中會丟失圖像。 接下來,我安裝了 inkscape 並運行了一個灰度命令,該命令似乎可以正常工作,但沒有修改example.svg
。 使用枕頭圖像的第三次嘗試未加載.svg
。
# 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 function 的 cairosvg。 然后,使用 Pillow 加載 png 文件並將其轉換為 np.array,然后您可以使用 openCV 輕松加載它並像您一樣將其轉換為灰度。 最后,您可以使用 svglib 和 reportlab 導出 svg 中的圖像。 使用此代碼段作為示例: https://stackoverflow.com/a/62345450/13605264
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.