Crop the image based on the normalized coordinates. Return the cropped image. This has the effect of zooming in on the image crop. Args: image (PIL.Image.Image): the input image x (float): the horizontal coordinate of the upper-left corner of the box y (float): t
(image, x:float, y:float, width:float, height:float)
| 3 | import json |
| 4 | |
| 5 | def crop_image(image, x:float, y:float, width:float, height:float): |
| 6 | """Crop the image based on the normalized coordinates. |
| 7 | Return the cropped image. |
| 8 | This has the effect of zooming in on the image crop. |
| 9 | |
| 10 | Args: |
| 11 | image (PIL.Image.Image): the input image |
| 12 | x (float): the horizontal coordinate of the upper-left corner of the box |
| 13 | y (float): the vertical coordinate of that corner |
| 14 | width (float): the box width |
| 15 | height (float): the box height |
| 16 | |
| 17 | Returns: |
| 18 | cropped_img (PIL.Image.Image): the cropped image |
| 19 | |
| 20 | Example: |
| 21 | image = Image.open("sample_img.jpg") |
| 22 | cropped_img = crop_image(image, 0.2, 0.3, 0.5, 0.4) |
| 23 | display(cropped_img) |
| 24 | """ |
| 25 | |
| 26 | # get height and width of image |
| 27 | w, h = image.size |
| 28 | |
| 29 | # limit the range of x and y |
| 30 | x = min(max(0, x), 1) |
| 31 | y = min(max(0, y), 1) |
| 32 | x2 = min(max(0, x+width), 1) |
| 33 | y2 = min(max(0, y+height), 1) |
| 34 | |
| 35 | cropped_img = image.crop((x*w, y*h, x2*w, y2*h)) |
| 36 | |
| 37 | buffer = io.BytesIO() |
| 38 | cropped_img.save(buffer, format="JPEG") |
| 39 | buffer.seek(0) # Reset buffer position |
| 40 | |
| 41 | # Load as a JpegImageFile |
| 42 | jpeg_image = Image.open(buffer) |
| 43 | return jpeg_image |
| 44 | |
| 45 | |
| 46 | def zoom_in_image_by_bbox(image, box, padding=0.01): |
no test coverage detected