Skip to content

Commit 8a041bd

Browse files
author
Matt Sokoloff
committed
mal notebooks
1 parent 0dd91b5 commit 8a041bd

File tree

8 files changed

+1532
-30
lines changed

8 files changed

+1532
-30
lines changed

examples/basics/Ontology.ipynb

Lines changed: 325 additions & 22 deletions
Large diffs are not rendered by default.

examples/basics/README.MD

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,4 @@
1111
3. Datasets
1212
- Other concepts: Tasks
1313
4. Ontology
14-
5. Labeling Front End
1514
6. Projects

examples/basics/data_rows.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@
248248
"metadata": {},
249249
"outputs": [],
250250
"source": [
251-
"datarow.delete(cklvfn909149e0y9n3xjbgtct)\n",
251+
"datarow.delete()\n",
252252
"#Will remove from the dataset too"
253253
]
254254
},

examples/basics/projects.ipynb

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
},
3737
{
3838
"cell_type": "code",
39-
"execution_count": 10,
39+
"execution_count": 1,
4040
"id": "herbal-examination",
4141
"metadata": {},
4242
"outputs": [],
@@ -55,7 +55,7 @@
5555
},
5656
{
5757
"cell_type": "code",
58-
"execution_count": 14,
58+
"execution_count": 2,
5959
"id": "super-notification",
6060
"metadata": {},
6161
"outputs": [],
@@ -74,7 +74,7 @@
7474
},
7575
{
7676
"cell_type": "code",
77-
"execution_count": 26,
77+
"execution_count": 3,
7878
"id": "secondary-marine",
7979
"metadata": {},
8080
"outputs": [
@@ -87,8 +87,8 @@
8787
"Project description: a description\n",
8888
"Dataset: []\n",
8989
"{'tools': [], 'classifications': []}\n",
90-
"Reviews: <labelbox.pagination.PaginatedCollection object at 0x112163df0>\n",
91-
"Benchmarks: <labelbox.pagination.PaginatedCollection object at 0x1121635b0>\n"
90+
"Reviews: <labelbox.pagination.PaginatedCollection object at 0x10fb6af40>\n",
91+
"Benchmarks: <labelbox.pagination.PaginatedCollection object at 0x112cac610>\n"
9292
]
9393
}
9494
],
@@ -114,7 +114,7 @@
114114
},
115115
{
116116
"cell_type": "code",
117-
"execution_count": 29,
117+
"execution_count": 4,
118118
"id": "lined-circuit",
119119
"metadata": {},
120120
"outputs": [
@@ -134,6 +134,14 @@
134134
"ds.delete()"
135135
]
136136
},
137+
{
138+
"cell_type": "code",
139+
"execution_count": null,
140+
"id": "connected-impression",
141+
"metadata": {},
142+
"outputs": [],
143+
"source": []
144+
},
137145
{
138146
"cell_type": "markdown",
139147
"id": "statistical-mission",

examples/model_assisted_labeling/image_mal.ipynb

Lines changed: 563 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import cv2
2+
import numpy as np
3+
import requests
4+
from io import BytesIO
5+
from PIL import Image
6+
7+
def visualize_bbox_upload(image, bbox_ndjsons, color):
8+
for bbox_ndjson in bbox_ndjsons:
9+
bbox = bbox_ndjson['bbox']
10+
start_point = (int(bbox['left']), int(bbox['top']))
11+
end_point = (int(bbox['left'] + bbox['width']), int(bbox['top'] + bbox['height']))
12+
image = cv2.rectangle(image, start_point, end_point, thickness = 2, color = color)
13+
return image
14+
15+
def visualize_poly_upload(image, poly_ndjsons, color):
16+
for poly_ndjson in poly_ndjsons:
17+
pts = [[poly['x'], poly['y']] for poly in poly_ndjson['polygon']]
18+
pts = np.array(pts).astype(np.int32)
19+
image = cv2.polylines(image,[pts],True,color, thickness = 2)
20+
return image
21+
22+
def visualize_point_upload(image, point_ndjsons, color):
23+
for point_ndjson in point_ndjsons:
24+
point = point_ndjson['point']
25+
image = cv2.circle(image, (point['x'],point['y']), radius=10, color=color, thickness=-1)
26+
return image
27+
28+
def visualize_mask_uploads(image, mask_ndjsons):
29+
masks = []
30+
for ndjson in mask_ndjsons:
31+
instanceURI = ndjson['mask']['instanceURI']
32+
masks.append(np.array(Image.open(BytesIO(requests.get(instanceURI).content))))
33+
masks = np.sum(masks, axis = 0).astype(np.uint8)
34+
return cv2.addWeighted(image, 0.7, masks, 0.3, 0)
35+
36+
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import tensorflow as tf
2+
import numpy as np
3+
import cv2
4+
5+
#https://colab.research.google.com/github/tensorflow/tpu/blob/master/models/official/mask_rcnn/mask_rcnn_demo.ipynb#scrollTo=2oZWLz4xXsyQ
6+
7+
class_mappings = {1: 'person', 3 : 'car', 28: 'umbrella', 31: 'handbag'}
8+
session = tf.compat.v1.Session()
9+
10+
def load_model():
11+
saved_model_dir = 'gs://cloud-tpu-checkpoints/mask-rcnn/1555659850'
12+
_ = tf.compat.v1.saved_model.loader.load(session, ['serve'], saved_model_dir)
13+
14+
15+
def predict(np_image_string, min_score, height, width):
16+
num_detections, detection_boxes, detection_classes, detection_scores, detection_masks, image_info = session.run(
17+
['NumDetections:0', 'DetectionBoxes:0', 'DetectionClasses:0', 'DetectionScores:0', 'DetectionMasks:0', 'ImageInfo:0'],
18+
feed_dict={'Placeholder:0': np_image_string})
19+
num_detections = np.squeeze(num_detections.astype(np.int32), axis=(0,))
20+
detection_scores = np.squeeze(detection_scores, axis=(0,))[0:num_detections]
21+
response = {
22+
'boxes' : np.squeeze(detection_boxes * image_info[0, 2], axis=(0,))[0:num_detections],
23+
'class_indices' : np.squeeze(detection_classes.astype(np.int32), axis=(0,))[0:num_detections],
24+
}
25+
ymin, xmin, ymax, xmax = np.split(response['boxes'], 4, axis=-1)
26+
instance_masks = np.squeeze(detection_masks, axis=(0,))[0:num_detections]
27+
processed_boxes = np.concatenate([xmin, ymin, xmax - xmin, ymax - ymin], axis=-1)
28+
response.update({'seg_masks' : generate_segmentation_from_masks(instance_masks, processed_boxes, height, width)})
29+
keep_indices = detection_scores > min_score
30+
keep_indices = keep_indices & np.isin(response['class_indices'], list(class_mappings.keys()))
31+
for key in response:
32+
response[key] = response[key][keep_indices]
33+
return response
34+
35+
36+
def expand_boxes(boxes, scale):
37+
"""Expands an array of boxes by a given scale."""
38+
# Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/boxes.py#L227 # pylint: disable=line-too-long
39+
# The `boxes` in the reference implementation is in [x1, y1, x2, y2] form,
40+
# whereas `boxes` here is in [x1, y1, w, h] form
41+
w_half = boxes[:, 2] * .5
42+
h_half = boxes[:, 3] * .5
43+
x_c = boxes[:, 0] + w_half
44+
y_c = boxes[:, 1] + h_half
45+
46+
w_half *= scale
47+
h_half *= scale
48+
49+
boxes_exp = np.zeros(boxes.shape)
50+
boxes_exp[:, 0] = x_c - w_half
51+
boxes_exp[:, 2] = x_c + w_half
52+
boxes_exp[:, 1] = y_c - h_half
53+
boxes_exp[:, 3] = y_c + h_half
54+
55+
return boxes_exp
56+
57+
def generate_segmentation_from_masks(masks,
58+
detected_boxes,
59+
image_height,
60+
image_width,
61+
is_image_mask=False):
62+
"""Generates segmentation result from instance masks.
63+
Args:
64+
masks: a numpy array of shape [N, mask_height, mask_width] representing the
65+
instance masks w.r.t. the `detected_boxes`.
66+
detected_boxes: a numpy array of shape [N, 4] representing the reference
67+
bounding boxes.
68+
image_height: an integer representing the height of the image.
69+
image_width: an integer representing the width of the image.
70+
is_image_mask: bool. True: input masks are whole-image masks. False: input
71+
masks are bounding-box level masks.
72+
Returns:
73+
segms: a numpy array of shape [N, image_height, image_width] representing
74+
the instance masks *pasted* on the image canvas.
75+
"""
76+
77+
78+
_, mask_height, mask_width = masks.shape
79+
scale = max((mask_width + 2.0) / mask_width,
80+
(mask_height + 2.0) / mask_height)
81+
82+
ref_boxes = expand_boxes(detected_boxes, scale)
83+
ref_boxes = ref_boxes.astype(np.int32)
84+
padded_mask = np.zeros((mask_height + 2, mask_width + 2), dtype=np.float32)
85+
segms = []
86+
for mask_ind, mask in enumerate(masks):
87+
im_mask = np.zeros((image_height, image_width), dtype=np.uint8)
88+
if is_image_mask:
89+
# Process whole-image masks.
90+
im_mask[:, :] = mask[:, :]
91+
else:
92+
# Process mask inside bounding boxes.
93+
padded_mask[1:-1, 1:-1] = mask[:, :]
94+
95+
ref_box = ref_boxes[mask_ind, :]
96+
w = ref_box[2] - ref_box[0] + 1
97+
h = ref_box[3] - ref_box[1] + 1
98+
w = np.maximum(w, 1)
99+
h = np.maximum(h, 1)
100+
101+
mask = cv2.resize(padded_mask, (w, h))
102+
mask = np.array(mask > 0.5, dtype=np.uint8)
103+
104+
x_0 = max(ref_box[0], 0)
105+
x_1 = min(ref_box[2] + 1, image_width)
106+
y_0 = max(ref_box[1], 0)
107+
y_1 = min(ref_box[3] + 1, image_height)
108+
109+
im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - ref_box[1]):(y_1 - ref_box[1]), (
110+
x_0 - ref_box[0]):(x_1 - ref_box[0])]
111+
segms.append(im_mask)
112+
113+
segms = np.array(segms)
114+
assert masks.shape[0] == segms.shape[0]
115+
return segms
116+
117+
118+
119+
120+

0 commit comments

Comments
 (0)