summaryrefslogtreecommitdiff
path: root/util/util.py
diff options
context:
space:
mode:
Diffstat (limited to 'util/util.py')
-rw-r--r--util/util.py20
1 files changed, 20 insertions, 0 deletions
diff --git a/util/util.py b/util/util.py
index 7a452a6..1c03715 100644
--- a/util/util.py
+++ b/util/util.py
@@ -54,3 +54,23 @@ def mkdirs(paths):
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
+
+def crop_image(img, xy, scale_factor):
+ '''Crop the image around the tuple xy
+
+ Inputs:
+ -------
+ img: Image opened with PIL.Image
+ xy: tuple with relative (x,y) position of the center of the cropped image
+ x and y shall be between 0 and 1
+ scale_factor: the ratio between the original image's size and the cropped image's size
+ '''
+ center = (img.size[0] * xy[0], img.size[1] * xy[1])
+ new_size = (img.size[0] / scale_factor, img.size[1] / scale_factor)
+ left = max (0, (int) (center[0] - new_size[0] / 2))
+ right = min (img.size[0], (int) (center[0] + new_size[0] / 2))
+ upper = max (0, (int) (center[1] - new_size[1] / 2))
+ lower = min (img.size[1], (int) (center[1] + new_size[1] / 2))
+ cropped_img = img.crop((left, upper, right, lower))
+ return cropped_img
+