Skip to content

Commit

Permalink
Better crop
Browse files Browse the repository at this point in the history
  • Loading branch information
sbrunner committed Apr 12, 2019
1 parent 617dded commit 4a584c5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 19 deletions.
24 changes: 5 additions & 19 deletions process
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,11 @@ def crop_image( # pylint: disable=too-many-arguments
image: np.ndarray, x: int, y: int, width: int, height: int,
background: Union[Tuple[int], Tuple[int, int, int]]
) -> np.ndarray:
if x < 0:
indices = np.zeros(-x, dtype=int)
image = np.insert(image, indices, background, axis=1)
x = 0
if y < 0:
indices = np.zeros(-y, dtype=int)
image = np.insert(image, indices, background, axis=0)
y = 0

overflow_x = x + width - image.shape[1]
if overflow_x > 0:
indices = np.zeros(overflow_x, dtype=int) + image.shape[1]
image = np.insert(image, indices, background, axis=1)
overflow_y = y + height - image.shape[0]
if overflow_y > 0:
indices = np.zeros(overflow_y, dtype=int) + int(image.shape[0])
image = np.insert(image, indices, background, axis=0)

return image[y:y + height, x:x + width]
matrice = np.array([
[1.0, 0.0, -x],
[0.0, 1.0, -y],
])
return cv2.warpAffine(image, matrice, (int(round(width)), int(round(height))), borderValue=background)


class Context: # pylint: disable=too-many-instance-attributes
Expand Down
4 changes: 4 additions & 0 deletions tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ def check_image(root_folder, image, name):
def test_crop():
image = load_image('image-1.png')
root_folder = '/results/crop'
if not os.path.exists(root_folder):
os.makedirs(root_folder)
check_image(root_folder, process.crop_image(image, 100, 0, 100, 300, (255, 255, 255)), 'crop-1')
check_image(root_folder, process.crop_image(image, 0, 100, 300, 100, (255, 255, 255)), 'crop-2')
check_image(root_folder, process.crop_image(image, 100, -100, 100, 200, (255, 255, 255)), 'crop-3')
Expand All @@ -59,6 +61,8 @@ def test_crop():
def test_rotate():
image = load_image('image-1.png')
root_folder = '/results/rotate'
if not os.path.exists(root_folder):
os.makedirs(root_folder)
image = process.crop_image(image, 0, 50, 300, 200, (255, 255, 255))
check_image(root_folder, process.rotate_image(image, 10, (255, 255, 255)), 'rotate-1')
check_image(root_folder, process.rotate_image(image, -10, (255, 255, 255)), 'rotate-2')
Expand Down

0 comments on commit 4a584c5

Please sign in to comment.