Crop the input image into given size at given position. Args: patch(tuple): width and height of the patch position(list(str)): left_top, left_bottom, right_top, right_bottom and center.
(img, patch, position)
| 49 | |
| 50 | |
| 51 | def crop(img, patch, position): |
| 52 | '''Crop the input image into given size at given position. |
| 53 | |
| 54 | Args: |
| 55 | patch(tuple): width and height of the patch |
| 56 | position(list(str)): left_top, left_bottom, right_top, right_bottom |
| 57 | and center. |
| 58 | ''' |
| 59 | if img.size[0] < patch[0]: |
| 60 | raise Exception('img size[0] %d is smaller than patch[0]: %d' % |
| 61 | (img.size[0], patch[0])) |
| 62 | if img.size[1] < patch[1]: |
| 63 | raise Exception('img size[1] %d is smaller than patch[1]: %d' % |
| 64 | (img.size[1], patch[1])) |
| 65 | |
| 66 | if position == 'left_top': |
| 67 | left, upper = 0, 0 |
| 68 | elif position == 'left_bottom': |
| 69 | left, upper = 0, img.size[1] - patch[1] |
| 70 | elif position == 'right_top': |
| 71 | left, upper = img.size[0] - patch[0], 0 |
| 72 | elif position == 'right_bottom': |
| 73 | left, upper = img.size[0] - patch[0], img.size[1] - patch[1] |
| 74 | elif position == 'center': |
| 75 | left, upper = (img.size[0] - patch[0]) // 2, (img.size[1] - |
| 76 | patch[1]) // 2 |
| 77 | else: |
| 78 | raise Exception('position is wrong') |
| 79 | |
| 80 | box = (left, upper, left + patch[0], upper + patch[1]) |
| 81 | new_img = img.crop(box) |
| 82 | # print "crop to box %d,%d,%d,%d" % box |
| 83 | return new_img |
| 84 | |
| 85 | |
| 86 | def crop_and_resize(img, patch, position): |