Created
September 28, 2017 19:58
-
-
Save markloyman/a14eb7519b776cf3f52eb082e520a5d9 to your computer and use it in GitHub Desktop.
Random crop of an image and it's mask (crop is aware of mask region)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def crop(image, mask, min_size= 128): | |
# Determine New Size on Y axis | |
max_size_y = image.shape[0] | |
mask_y = np.where(np.sum(mask, axis=1)) | |
min_size_y = np.max(mask_y) - np.min(mask_y) | |
new_size_y = np.random.rand() * (max_size_y - min_size_y) | |
new_size_y = np.maximum(new_size_y, min_size).astype('uint16') | |
# Determine New Size on X axis | |
max_size_x = image.shape[1] | |
mask_x = np.where(np.sum(mask, axis=0)) | |
min_size_x = np.max(mask_x) - np.min(mask_x) | |
new_size_x = np.random.rand() * (max_size_x - min_size_x) | |
new_size_x = np.maximum(new_size_x, min_size).astype('uint16') | |
# Determine crop translation on Y axis | |
min_crop_start_y = np.maximum(0, np.max(mask_y) - new_size_y) | |
max_crop_start_y = np.minimum(np.min(mask_y), max_size_y - new_size_y) | |
crop_start_y = min_crop_start_y + np.random.rand() * (max_crop_start_y - min_crop_start_y) | |
crop_start_y = crop_start_y.astype('uint16') | |
# Determine crop translation on X axis | |
min_crop_start_x = np.maximum(0, np.max(mask_x) - new_size_x) | |
max_crop_start_x = np.minimum(np.min(mask_x), max_size_x - new_size_x) | |
crop_start_x = min_crop_start_x + np.random.rand() * (max_crop_start_x - min_crop_start_x) | |
crop_start_x = crop_start_x.astype('uint16') | |
new_image = image[crop_start_y:crop_start_y + new_size_y, crop_start_x:crop_start_x + new_size_x] | |
new_mask = mask[crop_start_y:crop_start_y + new_size_y, crop_start_x:crop_start_x + new_size_x] | |
return new_image, new_mask |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment