Skip to content

Instantly share code, notes, and snippets.

@dbazile
Last active November 5, 2016 02:20
Show Gist options
  • Save dbazile/334f6eb72dd5e61f9bc0d518b5891068 to your computer and use it in GitHub Desktop.
Save dbazile/334f6eb72dd5e61f9bc0d518b5891068 to your computer and use it in GitHub Desktop.

Input

jpg

Outputs

Pixel Replacement (aka brute force)

Time: 1.51s Replaced 875566 of 1819797 pixels

jpg

Geometry Mask

Time: 0.681s

jpg

from time import time
from PIL import Image, ImageDraw
def by_geometry_mask():
def to_percentage(coordinates, extent):
min_x, min_y, max_x, max_y = extent
points = []
for x, y in coordinates:
px = (x - min_x) / (max_x - min_x)
py = (y - min_y) / (max_y - min_y)
points.append((px, py))
return points
POINTS = to_percentage([[-3.207, 81.203], [2.307, 79.699], [-5.129, 78.838], [-11.194, 80.211], [-3.207, 81.203]], (-11.194, 78.838, 2.307, 81.203))
SCALE_FACTOR = 4
print('Geometry Mask:')
t = time()
img = Image.open('LC80010022016230LGN00_thumb_large.jpg') # type: Image.Image
w, h = img.size[0] * SCALE_FACTOR, img.size[1] * SCALE_FACTOR
mask = Image.new('L', (w, h), 255)
draw = ImageDraw.Draw(mask)
draw.polygon(list(map(lambda p: (p[0] * w, p[1] * h), POINTS)), fill=0)
# mask = ImageOps.invert(mask)
mask = mask.resize(img.size, resample=Image.ANTIALIAS)
img = img.convert('P', palette=Image.ADAPTIVE)
img.paste(0, mask=mask)
img.save('by geometry mask.png')
print(' Done in {:.3}s'.format(time() - t))
print()
def by_pixel_replacement():
print('Pixel Replacement:')
t = time()
img = Image.open('LC80010022016230LGN00_thumb_large.jpg') # type: Image.Image
img = img.convert('RGBA')
pixels = list(img.getdata())
dropped = 0
total = len(pixels)
for i, (r, g, b, a) in enumerate(pixels):
if r < 15 and g < 15 and b < 15:
dropped += 1
pixels[i] = (0, 0, 0, 0)
img.putdata(pixels)
img.save('by pixel replacement.png')
print(' Done in {:0.3}s (replaced {} of {} pixels)'.format(time() - t, dropped, total))
print()
by_pixel_replacement()
by_geometry_mask()
Display the source blob
Display the rendered blob
Raw
{
"type": "Feature",
"properties": {
"uri": "http://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_thumb_large.jpg"
},
"geometry": {
"type": "Polygon",
"coordinates": [[[-3.207,81.203],[2.307,79.699],[-5.129,78.838],[-11.194,80.211],[-3.207,81.203]]]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment