Skip to content

Instantly share code, notes, and snippets.

@yosemitebandit
Created November 18, 2015 04:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yosemitebandit/03bb3ae302582d9dc6be to your computer and use it in GitHub Desktop.
Save yosemitebandit/03bb3ae302582d9dc6be to your computer and use it in GitHub Desktop.
cut an image out based on a path in python with Pillow, Numpy and Shapely
"""Crop a polygonal selection from an image."""
import numpy as np
from PIL import Image
from shapely.geometry import Point
from shapely.geometry import Polygon
im = Image.open('bird.jpg').convert('RGBA')
pixels = np.array(im)
im_copy = np.array(im)
region = Polygon([(200, 200), (450, 400), (50, 550)])
for index, pixel in np.ndenumerate(pixels):
# Unpack the index.
row, col, channel = index
# We only need to look at spatial pixel data for one of the four channels.
if channel != 0:
continue
point = Point(row, col)
if not region.contains(point):
im_copy[(row, col, 0)] = 255
im_copy[(row, col, 1)] = 255
im_copy[(row, col, 2)] = 255
im_copy[(row, col, 3)] = 0
cut_image = Image.fromarray(im_copy)
cut_image.save('bird.png')
@TarunNagaSai
Copy link

can i get this in circle???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment