How can you crop an SVG Image in Python? - python

With a program, I am producing an SVG image with dimensions of 400px x 400px. However, I would like to crop the bottom of this SVG image off, based off of a variable that dictates how much of the bottom of the image should be cropped in pixels.
This SVG image is being generated with pyCairo with surface = cairo.SVGSurface("output.svg", WIDTH, HEIGHT) and ctx = cairo.Context(surface).
Although the HEIGHT variable is a constant and isn't changed, after I perform some operations on the surface object, I would like to be able to resize it once more. I can use the Pillow Image object to crop PNGs, but it does not support SVGs.
I have also tried to open the svg file with open("output.svg"). However, if I try to read it, I am unable to and it shows up as blank, thus making it unmodifiable.
Is there any way in Python to either crop an SVG image or modify its size after it has been modified with pycairo?

The answer above is incomplete and at least for me doesn't solve the problem.
A SVG can simply be cropped (trimmed, clipped, cut) using vpype with the crop or trim and translate commands.
import vpype_cli as vp
#vp.excute("read test.svg translate 300 400 trim 30 20 write output.svg")
vpype_cli.execute("read test.svg crop 0cm 0cm 10cm 20cm write output.svg")
Playing around with the parameters should lead to the desired crop.
Took some time to find this, as most answers say it cant be done, which is ridiculous.

You cannot crop SVG like you crop PNG because in the latter you can just drop pixels, while for the former you have defined paths that can't be easily recomputed.
If you're sure there's nothing in the part you are about to "crop", you can use set_context_size to make the svg context/canvas smaller while preserving ratio and size inside.

Related

Find Coordinates of cropped image (JPG) from it's original

I have a database of original images and for each original images there are various cropped versions.
This is an example of how the image look like:
Original
Horizontal Crop
Square Crop
This is a very simple example, but most images are like this, some might taken a smaller section of the original image than others.
I was looking at OpenCV in python but I'm very new to this kind of image processing.
The idea is to be able to save the cropping information separate from the image to save space and then generate all the cropping and different aspect ratio on the fly with a cache system instead.
The method you are looking for is called "template matching". You find examples here
https://docs.opencv.org/trunk/d4/dc6/tutorial_py_template_matching.html
For your problem, given the large images, it might be a good idea to constrain the search space by resizing both images by the same factor. So that searching a position that isn't as precise, but allows then to constrain the actual full pixel sized search to a smaller region around that point.

Produce a composed image with different sized layers with transparency

I'm very new to Python and am exploring it's use to allow users to build custom images. The idea is that the client would select a few options and the image would be created on the server then downloaded (or used for other things on the server side).
The image is composed of many images, most of which are small icon type of images that are irregular shapes and have transparency. All layers are .png files.
I've tried using Pillow but it seems the image needs to be the same size as the overall image to properly use the transparency of the top layers.
Here's what I've tried so far:
from PIL import Image
background = Image.open("Background.png")
foreground = Image.open("Trim.png")
fire = Image.open("Type_Fire_Large.png")
background = Image.alpha_composite(background, foreground)
background.paste(fire, (150, 150))
background.show()
The image looks like this:
Background.png is the shaded "noise" and Trim.png is the grey diagonal lines. The best part: Trim.png has the center transparent and is able to show Background.png in the middle. But it's also the same size as the image.
The problem is Fire; notice how theres that black border (and odd fuchsia dot). The documentation states that the overlay image needs to be the same size. But it seems like a common scenario where someone would want to place a smaller icon with transparency on top of another image and compose them into one image.
I'm not attached to any particular library, I'm wide open to ideas and alternatives. The only thing I'm trying to do is keep it simple, so creating an entire game engine or the like to produce an image would probably be too much.
To just paste one png on top of another, respecting transparency, try
background.paste(fire, (x,y), fire.convert("RGBA"))
First I'd say Johannes Holmberg already answered your main concern: The missing transparency.
But I can hopefully explain what it's about with that odd fuchsia dot:
A transparent color image is usually stored as RGBA (RGB for Red, Green, Blue and A for Alpha). Here Alpha defines the transparency, from no transparency to full transparency.
Overlaying the images the correct way we see the GIMP Logo but the color stripe is almost invisible - because it's (almost) transparent.
But - as every pixel could be possibly visible - every pixel does still have a color. Even those pixels with 100% transparency. Thus, if we do not take Alpha into consideration we see each pixel color without transparency. This way we might have disturbing colors that are usually not disturbing at all - as long as they are fully transparent.

Automatic extract subimage with a frame

I am trying to extract a subimage from a scanned paper like this:
https://cloud.kopa.ch/index.php/s/gGZm5xeMYlPfU81
The extracted images should be georeferenced and added to a webmap service, but thats not the question here.
How can I get the frame / its pixel coordinates to crop the image?
I am also free in creating the "layout" (similar to the example), which means I could add markers to get the frame better after scanning it again.
The workflow is:
generate layout - print map - draw on the map - scan it - crop "map-frame" - georeferencing this frame - show it on a webmap
The "map-frames" are preprocessed and I know their location/extent
Has anybody an idea how to crop the (scanned) images automatically to this "map-frame"?
I have to work with python and have the packages PIL, pillow and imagemagick for the image processing
Thanks for you help!
If you need more information, don't hesitate to ask
Here's an example I adapted form the Pillow docs, check them out for any further processing that you might need to perform:
from Pillow import Image
Image.open("/path/to/image.jpg")
box = (100, 100, 400, 400)
region = im.crop(box)
Also, it might prove valuable to search Stack Overflow for this kind of operation, I'm sure it has been discussed earlier.
As for finding the actual rectangle to crop you'll have to do some form of image analysis. In it's simplest form, conceptually that could be something along these lines:
Applying an S-curve filter to a black-and-white representation of your image
Iterate over all of the pixels in the image
Keep track of horizontal and vertical lines that has sufficiently black pixel values.
Use this data to determine the bounding box of the portion of the image your interested in.
Depending on your needs you might want to look into some computer vision library instead, which are well optimized for this and similar tasks. The one that springs to mind is OpenCV which is I would guess is well optimized and documented, and there's a python module available as well.

PIL: overlaying images with different dimensions and aspect ratios

I've been attempting to overlay two images in python to match coordinates, the top left and bottom right corners have the same coordinates and their aspects are almost identical bar a few pixels. Although they are different resolutions.
Using PIL I have been able to overlay the images, though after overlaying them the image output is square but the resolution is that of the background image, the foreground image is also re-sized incorrectly (As far as I can see). I must be doing something wrong.
import Image
from PIL import Image
#load images
background = Image.open('ndvi.png')
foreground = Image.open('out.png')
#resizing
foreground.thumbnail((643,597),Image.ANTIALIAS)
#overlay
background.paste(foreground, (0, 0), foreground)
#save
background.save("overlay.png")
#display
background.show()
When dropping the images into something horrible like powerpoint the image aspects are almost identical. I've included an example image, the image on the left is my by hand overlay and the image on the right is the output from python. The background at some point in the code is squashed vertically, also affecting the overlay. I'd like to be able to do this in python and make it correctly look like the left hand image.
A solution upfront.
Background image
width/height/ratio: 300 / 375 / 0.800
Foreground image
width/height/ratio: 400 / 464 / 0.862
Overlay
from PIL import Image
imbg = Image.open("bg.png")
imfg = Image.open("fg.png")
imbg_width, imbg_height = imbg.size
imfg_resized = imfg.resize((imbg_width, imbg_height), Image.LANCZOS)
imbg.paste(imfg_resized, None, imfg_resized)
imbg.save("overlay.png")
Discussion
The most important information you have given in your question were:
the aspect ratios of your foreground and background images are not equal, but similar
the top left and bottom right corners of both images need to be aligned in the end.
The conclusion from these points is: the aspect ratio of one of the images has to change. This can be achieved with the resize() method (not with thumbnail(), as explained below). To summarize, the goal simply is:
Resize the image with larger dimensions (foreground image) to the exact dimensions of the smaller background image. That is, do not necessarily maintain the aspect ratio of the foreground image.
That is what the code above is doing.
Two comments on your approach:
First of all, I recommend using the newest release of Pillow (Pillow is the continuation project of PIL, it is API-compatible). In the 2.7 release they have largely improved the image re-scaling quality. The documentation can be found at http://pillow.readthedocs.org/en/latest/reference.
Then, you obviously need to take control of how the aspect ratio of both images evolves throughout your program. thumbnail(), for instance, does not alter the aspect ratio of the image, even if your size tuple does not have the same aspect ratio as the original image. Quote from the thumbnail() docs:
This method modifies the image to contain a thumbnail version of
itself, no larger than the given size. This method calculates an
appropriate thumbnail size to preserve the aspect of the image
So, I am not sure where you were going exactly with your (643,597) tuple and if you are possibly relying on the thumbnail to have this exact size afterwards.

extending an image with Python Imaging Library

I am trying to increase the height of an image using PIL but I don't want the image to be resized; I actually want a strip of blank pixels at the bottom of the image. Any way of doing this with PIL?
I guess one way would be to make a new image of the required size and copy the old image into it but I can't seem to find the right function to do this.
Oops, just realized you can do image.crop() and it will resize the image for you.

Categories

Resources