Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polygon crop/clip using Python / PIL

The polygon points along with the uncut, original image are sent by client to the server.

Is there a way that I can clip (crop) the original image along these points in Python server, and save the cropped image? I am currently using PIL, and would prefer a PIL or PIL extended solution.

Thanks in advance

like image 962
user2667409 Avatar asked Mar 23 '14 07:03

user2667409


People also ask

How do I crop an image using Python PIL?

crop() method is used to crop a rectangular portion of any image. Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate. Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple).

How do I crop an image to a specific size in Python?

Use resize() to resize the whole image instead of cutting out a part of the image, and use putalpha() to create a transparent image by cutting out a shape other than a rectangle (such as a circle). Use slicing to crop the image represented by the NumPy array ndarray . Import Image from PIL and open the target image.

What is PIL image in Python?

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image.


1 Answers

I found a solution using numpy and PIL- so thought I will share:

import numpy
from PIL import Image, ImageDraw

# read image as RGB and add alpha (transparency)
im = Image.open("crop.jpg").convert("RGBA")

# convert to numpy (for convenience)
imArray = numpy.asarray(im)

# create mask
polygon = [(444,203),(623,243),(691,177),(581,26),(482,42)]
maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1)
mask = numpy.array(maskIm)

# 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("out.png")
like image 186
user2667409 Avatar answered Sep 18 '22 13:09

user2667409