Trim asymmetric image area using Python / PIL

Is there a way to cut rectangular areas of non- images with Python PIL?

eg. In this picture I want to exclude all black areas, as well as towers, roofs and pillars.
http://img153.imageshack.us/img153/5330/skybig.jpg

I think the ImagePath module can do this, but also, how can I read the data, for example. svg file and convert it to a path?

Any help would be appreciated.


(My additional question, apparently, is an easier task: how to cut out at least a circle of an image?)

+4
source share
1 answer

If I understand correctly, you want to make some areas transparent inside the image. And these areas have a random shape. The easiest way (I can think of) is to create a mask and put it in the alpha channel of the image. Below is the code that shows how to do this.

If your question is: "How to create a polygon mask", I redirect you to:

SciPy Create a 2D Polygon Mask

and see the accepted answer.

w

Juha

import numpy import Image # read image as RGB and add alpha (transparency) im = Image.open("lena.png").convert("RGBA") # convert to numpy (for convenience) imArray = numpy.asarray(im) # create mask (zeros + circle with ones) center = (200,200) radius = 100 mask = numpy.zeros((imArray.shape[0],imArray.shape[1])) for i in range(imArray.shape[0]): for j in range(imArray.shape[1]): if (i-center[0])**2 + (j-center[0])**2 < radius**2: mask[i,j] = 1 # assemble new image (uint8: 0-255) newImArray = numpy.empty(imArray.shape,dtype='uint8') # colors (three first columns, RGB) newImArray[:,:,:3] = imArray[:,:,:3] # transparency (4th column) newImArray[:,:,3] = mask*255 # back to Image from numpy newIm = Image.fromarray(newImArray, "RGBA") newIm.save("lena3.png") 

Edit

In fact, I could not resist ... the solution to the polygon mask was so elegant (replace the above circle with this):

 # create mask polygon = [(100,100), (200,100), (150,150)] maskIm = Image.new('L', (imArray.shape[0], imArray.shape[1]), 0) ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1) mask = numpy.array(maskIm) 

Edit2

Now that I think about it. If you have black and white svg, you can upload your svg directly as a mask (if white is your mask). I do not have any svg image samples, so I cannot verify this. I'm not sure if PIL can open svg images.

+4
source

All Articles