Python SVG converter creates empty file - python

I have some code below that is supposed to convert a SVG image to a PNG. It runs without errors but creates a PNG file that is blank instead of one with the same image as the original SVG. I did find that it is not an error with cairo but more one relating to rsvg, which I got here.
import cairo
import rsvg
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)
ctx = cairo.Context(img)
handle= rsvghandler.Handle('example.svg')
handle.render_cairo(ctx)
img.write_to_png("svg.png")
I am using Python 3.6 on Windows 10.
I can't for the life of me figure out why it isn't displaying the correct picture. Any help would be hugely appreciated.

If your goal is to convert from SVG to PNG, I would recommend using Wand, as in the following script:
from wand.api import library
import wand.color
import wand.image
with wand.image.Image() as image:
with wand.color.Color('transparent') as background_color:
library.MagickSetBackgroundColor(image.wand,
background_color.resource)
image.read(blob=NAMEOFTHEFILE.read(), format="svg")
png_image = image.make_blob("png32")
with open(NAMEOFTHENEWFILE, "wb") as out:
out.write(png_image)

Related

How can I get a glyph with holes(Python)?

These are frameworks that I use:
from pdf2image import convert_from_path
from PIL import Image, ImageChops
import cv2
import numpy as np
from shapely.geometry import Polygon
import svgwrite
import json
from defcon import Font
import ufo2ft
from fontTools import svgLib
I have a svg file looks like the image below this sentence(The image is upside-down).
SVG file
I load this file and add to Defcon.Font like this:
glyph = font.newGlyph(name=korean_unicode_list[int(key)])
glyph.unicode = int(korean_unicode_list[int(key)], 16)
pen = glyph.getPen()
svg = svgLib.SVGPath("svg_files/" + str(key) + ".svg")
svg.draw(pen)
But after I export this Font object with ufo2ft, The glyph's hole has disappeared :(
ttf = ufo2ft.compileTTF(font)
ttf.save('myFont.ttf')
After Export
I don't know how to make holes at glyphs. I'm guessing that there is a solution at pen object and its methods, but there is no example about glyph with holes. How can I get a glyph with holes?
I got a solution myself :)
I tested with Adobe Illustrator. I made '0'-shaped object and saved in svg file. When I export a font file with the svg file, there was a hole.
So I opened the svg file at PyCharm, there's a option name 'xml:space'. If its option set to "preserve", svgPath can draw a path with holes.
I hope this article help you.

How do i read image using PILLOW image?

I wanted read a image using PIL.Image.open().But I've image in different path.
The following is the path I've the python script
"D:\YY_Aadhi\holy-edge-master\hed\test.py"
The following is the path I've the image file.
"D:\YY_Aadhi\HED-BSDS\test\2018.jpg"
from PIL import Image
'''some code here'''
image = Image.open(????)
How should I fill the question mark to access the image file.
you can simply do
from PIL import Image
image = Image.open("D:\\YY_Aadhi\\HED-BSDS\\test\\2018.jpg")
or
from PIL import Image
directory = "D:\\YY_Aadhi\\HED-BSDS\\test\\2018.jpg"
image = Image.open(directory)
like this.
you have to write escape sequence twice in windows, when you want to define as directory. and It will be great if you try some stupid code. It helps you a lot.
Does this image = Image.open("D:\YY_Aadhi\HED-BSDS\test\2018.jpg") not do the trick?
You can use this to read an online image
from urllib.request import urlopen
url = 'https://somewebsite/images/logo.png'
msg_image = urlopen(url).read()

How can I display .png file in a the Microsoft Azure Jupyter Notebook [duplicate]

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.
I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:
gd_diagram.write("test.png", "PNG")
display(file="test.png")
However, I can't figure out how to do this - or know if it's possible. So does anyone know if images can be opened/displayed in IPython?
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
(official docs)
If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.
from IPython.display import Image, display
listOfImageNames = ['/path/to/images/1.png',
'/path/to/images/2.png']
for imageName in listOfImageNames:
display(Image(filename=imageName))
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)
from IPython.display import display
from PIL import Image
path="/path/to/image.jpg"
display(Image.open(path))
You may need to install PIL
in Anaconda this is done by typing
conda install pillow
If you want to efficiently display big number of images I recommend using IPyPlot package
import ipyplot
ipyplot.plot_images(images_array, max_images=20, img_width=150)
There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.
You could use in html code in markdown section:
example:
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
If you are looking to embed your image into ipython notebook from the local host, you can do the following:
First: find the current local path:
# show current directory
import os
cwd = os.getcwd()
cwd
The result for example would be:
'C:\\Users\\lenovo\\Tutorials'
Next, embed your image as follows:
from IPython.display import display
from PIL import Image
path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))
Make sure that you choose the right image type among jpg, jpeg or png.
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
You can directly use this instead of importing PIL
from IPython.display import Image, display
display(Image(base_image_path))
Another opt is:
from matplotlib import pyplot as plt
from io import BytesIO
from PIL import Image
import Ipython
f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()
When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.
from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))
[See Notebook]
This is the solution using opencv-python, but it opens new windows which is busy in waiting
import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()
if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()

python3.5 PIL Image not displaying image

The following code does not display the image lists.jpg (in current dir):
print(dir(Image)) displays components; im.size, im.filename, im.format all return correct values.
What have I not done to display this jpg file?
from PIL import Image
im = Image.open("lists.jpg")
im.show() # did not work - perhaps due to the environment Jupyter Notebooks
Solution: replaced module with another with immediate results.
from IPython.display import Image
Image(filename='lists.jpg')
I know it is quite late to post but I will do it for new readers.
This problem arises in case of Jupyter Notebooks. Using show() does not display the image. So discard calling show() like in the code below. This will display the image in the output of the cell.
from PIL import Image
im = Image.open("lists.jpg")
im
To display the image on screen:
from PIL import Image
im = Image.open("lists.jpg")
im.show()
See also http://pillow.readthedocs.io/en/4.0.x/reference/Image.html

How can I display an image from a file in Jupyter Notebook?

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module. While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.
I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:
gd_diagram.write("test.png", "PNG")
display(file="test.png")
However, I can't figure out how to do this - or know if it's possible. So does anyone know if images can be opened/displayed in IPython?
Courtesy of this post, you can do the following:
from IPython.display import Image
Image(filename='test.png')
(official docs)
If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.
from IPython.display import Image, display
listOfImageNames = ['/path/to/images/1.png',
'/path/to/images/2.png']
for imageName in listOfImageNames:
display(Image(filename=imageName))
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)
from IPython.display import display
from PIL import Image
path="/path/to/image.jpg"
display(Image.open(path))
You may need to install PIL
in Anaconda this is done by typing
conda install pillow
If you want to efficiently display big number of images I recommend using IPyPlot package
import ipyplot
ipyplot.plot_images(images_array, max_images=20, img_width=150)
There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.
You could use in html code in markdown section:
example:
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
from IPython.display import Image
Image(filename =r'C:\user\path')
I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
If you are looking to embed your image into ipython notebook from the local host, you can do the following:
First: find the current local path:
# show current directory
import os
cwd = os.getcwd()
cwd
The result for example would be:
'C:\\Users\\lenovo\\Tutorials'
Next, embed your image as follows:
from IPython.display import display
from PIL import Image
path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))
Make sure that you choose the right image type among jpg, jpeg or png.
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
You can directly use this instead of importing PIL
from IPython.display import Image, display
display(Image(base_image_path))
Another opt is:
from matplotlib import pyplot as plt
from io import BytesIO
from PIL import Image
import Ipython
f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()
When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image. This can be wrapped using an IPython.display.Image object to make it display in the notebook.
from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))
[See Notebook]
This is the solution using opencv-python, but it opens new windows which is busy in waiting
import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()
if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()

Categories

Resources