-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnotebook_utils.py
More file actions
71 lines (53 loc) · 1.88 KB
/
notebook_utils.py
File metadata and controls
71 lines (53 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import io
import re
from typing import Tuple
from ipywidgets.widgets.widget_upload import FileUpload
import PIL.Image
import PIL.ImageDraw
class ErrorMessage:
UPLOAD_ERROR = 'No image uploaded.'
BOUNDS_ERROR = 'Could not extract bounds from string {string}.'
def __init__(self):
pass
Coordinate = Tuple[int, int]
def get_uploaded_image(uploader: FileUpload) -> PIL.Image.Image:
if not uploader.value:
raise ValueError(ErrorMessage.UPLOAD_ERROR)
file_info = next(iter(uploader.value.values()))
image = PIL.Image.open(io.BytesIO(file_info['content'])).convert('RGB')
return image
def parse_bounds(bound_string: str) -> Tuple[Coordinate, Coordinate]:
regex = r'\[([0-9]+),([0-9]+)\]\[([0-9]+),([0-9]+)\]'
m = re.match(regex, bound_string)
if m is None:
raise ValueError(ErrorMessage.BOUNDS_ERROR.format(string=bound_string))
top_left = (int(m.group(1)), int(m.group(2)))
bottom_right = (int(m.group(3)), int(m.group(4)))
return top_left, bottom_right
def draw_bounding_box(
image: PIL.Image.Image,
top_left: Coordinate,
bottom_right: Coordinate,
) -> PIL.Image.Image:
duplicate_image = image.copy()
draw = PIL.ImageDraw.Draw(duplicate_image)
draw.rectangle([top_left, bottom_right], outline="red", width=10)
return duplicate_image
def crop_image(
image: PIL.Image.Image,
top_left: Coordinate,
bottom_right: Coordinate,
) -> PIL.Image.Image:
return image.crop([*top_left, *bottom_right])
def convert_image_to_bytes(image: PIL.Image.Image) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format='PNG')
return buffer.getvalue()
def get_bottom_right(
image: PIL.Image.Image,
top_left: Coordinate,
) -> Coordinate:
width, height = image.size
bottom = top_left[1] + height
right = top_left[0] + width
return right, bottom