Time: 1.51s
Replaced 875566 of 1819797 pixels
Time: 0.681s
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() |