Skip to content

Instantly share code, notes, and snippets.

@aragaer
Created December 28, 2018 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aragaer/68f0ce8b9c2433482794d85f1225c1f3 to your computer and use it in GitHub Desktop.
Save aragaer/68f0ce8b9c2433482794d85f1225c1f3 to your computer and use it in GitHub Desktop.
Determine weight of each overlapping block
#!/usr/bin/env python
import argparse
import glob
import os
import sys
import numpy as np
from PIL import Image
SIZE_X = 128
SIZE_Y = 128
OFFT_X = 64
OFFT_Y = 64
_resize = False
def load_image(path):
image = Image.open(path)
width, height = image.size
if not _resize:
return image
if height < width:
new_height = SIZE_X
ratio = height/SIZE_X
new_width = int(width / ratio)
else:
new_width = SIZE_Y
ratio = width/SIZE_Y
new_height = int(height / ratio)
return image.resize((new_width, new_height))
def cut_image(path_or_image):
if isinstance(path_or_image, str):
image = load_image(path_or_image)
else:
image = path_or_image
width, height = image.size
top = 0
bottom = 0
while bottom < height:
bottom = top + SIZE_Y
if bottom > height:
bottom = height
top = height - SIZE_Y
left = 0
right = 0
while right < width:
right = left + SIZE_X
if right > width:
right = width
left = width - SIZE_X
yield (left, top, right, bottom)
left += OFFT_X
top += OFFT_Y
def cut(opts):
for opt in opts:
for name in glob.glob(os.path.expanduser(opt)):
image = load_image(name)
overlap = np.zeros(image.size)
boxes = list(cut_image(image))
for left, top, right, bottom in boxes:
overlap[left:right, top:bottom] += 1
print(name)
for left, top, right, bottom in boxes:
print("{}-{}:{}-{}".format(left, top, right, bottom),
np.average(1/overlap[left:right, top:bottom]))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--resize", action='store_true')
args, opts = parser.parse_known_args()
_resize = args.resize
cut(opts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment