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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__author__ = "licheng"
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
This interface provides access to four datasets:
|
| 5 |
+
1) refclef
|
| 6 |
+
2) refcoco
|
| 7 |
+
3) refcoco+
|
| 8 |
+
4) refcocog
|
| 9 |
+
split by unc and google
|
| 10 |
+
|
| 11 |
+
The following API functions are defined:
|
| 12 |
+
REFER - REFER api class
|
| 13 |
+
getRefIds - get ref ids that satisfy given filter conditions.
|
| 14 |
+
getAnnIds - get ann ids that satisfy given filter conditions.
|
| 15 |
+
getImgIds - get image ids that satisfy given filter conditions.
|
| 16 |
+
getCatIds - get category ids that satisfy given filter conditions.
|
| 17 |
+
loadRefs - load refs with the specified ref ids.
|
| 18 |
+
loadAnns - load anns with the specified ann ids.
|
| 19 |
+
loadImgs - load images with the specified image ids.
|
| 20 |
+
loadCats - load category names with the specified category ids.
|
| 21 |
+
getRefBox - get ref's bounding box [x, y, w, h] given the ref_id
|
| 22 |
+
showRef - show image, segmentation or box of the referred object with the ref
|
| 23 |
+
getMask - get mask and area of the referred object given ref
|
| 24 |
+
showMask - show mask of the referred object given ref
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import itertools
|
| 28 |
+
import json
|
| 29 |
+
import os.path as osp
|
| 30 |
+
import pickle
|
| 31 |
+
import sys
|
| 32 |
+
import time
|
| 33 |
+
from pprint import pprint
|
| 34 |
+
|
| 35 |
+
import matplotlib.pyplot as plt
|
| 36 |
+
import numpy as np
|
| 37 |
+
import skimage.io as io
|
| 38 |
+
from matplotlib.collections import PatchCollection
|
| 39 |
+
from matplotlib.patches import Polygon, Rectangle
|
| 40 |
+
from pycocotools import mask
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class REFER:
|
| 44 |
+
def __init__(self, data_root, dataset="refcoco", splitBy="unc"):
|
| 45 |
+
# provide data_root folder which contains refclef, refcoco, refcoco+ and refcocog
|
| 46 |
+
# also provide dataset name and splitBy information
|
| 47 |
+
# e.g., dataset = 'refcoco', splitBy = 'unc'
|
| 48 |
+
print("loading dataset %s into memory..." % dataset)
|
| 49 |
+
self.ROOT_DIR = osp.abspath(osp.dirname(__file__))
|
| 50 |
+
self.DATA_DIR = osp.join(data_root, dataset)
|
| 51 |
+
if dataset in ["refcoco", "refcoco+", "refcocog"]:
|
| 52 |
+
self.IMAGE_DIR = osp.join(data_root, "images/mscoco/images/train2014")
|
| 53 |
+
elif dataset == "refclef":
|
| 54 |
+
self.IMAGE_DIR = osp.join(data_root, "images/saiapr_tc-12")
|
| 55 |
+
else:
|
| 56 |
+
print("No refer dataset is called [%s]" % dataset)
|
| 57 |
+
sys.exit()
|
| 58 |
+
|
| 59 |
+
self.dataset = dataset
|
| 60 |
+
|
| 61 |
+
# load refs from data/dataset/refs(dataset).json
|
| 62 |
+
tic = time.time()
|
| 63 |
+
|
| 64 |
+
ref_file = osp.join(self.DATA_DIR, "refs(" + splitBy + ").p")
|
| 65 |
+
print("ref_file: ", ref_file)
|
| 66 |
+
self.data = {}
|
| 67 |
+
self.data["dataset"] = dataset
|
| 68 |
+
self.data["refs"] = pickle.load(open(ref_file, "rb"))
|
| 69 |
+
|
| 70 |
+
# load annotations from data/dataset/instances.json
|
| 71 |
+
instances_file = osp.join(self.DATA_DIR, "instances.json")
|
| 72 |
+
instances = json.load(open(instances_file, "rb"))
|
| 73 |
+
self.data["images"] = instances["images"]
|
| 74 |
+
self.data["annotations"] = instances["annotations"]
|
| 75 |
+
self.data["categories"] = instances["categories"]
|
| 76 |
+
|
| 77 |
+
# create index
|
| 78 |
+
self.createIndex()
|
| 79 |
+
print("DONE (t=%.2fs)" % (time.time() - tic))
|
| 80 |
+
|
| 81 |
+
def createIndex(self):
|
| 82 |
+
# create sets of mapping
|
| 83 |
+
# 1) Refs: {ref_id: ref}
|
| 84 |
+
# 2) Anns: {ann_id: ann}
|
| 85 |
+
# 3) Imgs: {image_id: image}
|
| 86 |
+
# 4) Cats: {category_id: category_name}
|
| 87 |
+
# 5) Sents: {sent_id: sent}
|
| 88 |
+
# 6) imgToRefs: {image_id: refs}
|
| 89 |
+
# 7) imgToAnns: {image_id: anns}
|
| 90 |
+
# 8) refToAnn: {ref_id: ann}
|
| 91 |
+
# 9) annToRef: {ann_id: ref}
|
| 92 |
+
# 10) catToRefs: {category_id: refs}
|
| 93 |
+
# 11) sentToRef: {sent_id: ref}
|
| 94 |
+
# 12) sentToTokens: {sent_id: tokens}
|
| 95 |
+
print("creating index...")
|
| 96 |
+
# fetch info from instances
|
| 97 |
+
Anns, Imgs, Cats, imgToAnns = {}, {}, {}, {}
|
| 98 |
+
for ann in self.data["annotations"]:
|
| 99 |
+
Anns[ann["id"]] = ann
|
| 100 |
+
imgToAnns[ann["image_id"]] = imgToAnns.get(ann["image_id"], []) + [ann]
|
| 101 |
+
for img in self.data["images"]:
|
| 102 |
+
Imgs[img["id"]] = img
|
| 103 |
+
for cat in self.data["categories"]:
|
| 104 |
+
Cats[cat["id"]] = cat["name"]
|
| 105 |
+
|
| 106 |
+
# fetch info from refs
|
| 107 |
+
Refs, imgToRefs, refToAnn, annToRef, catToRefs = {}, {}, {}, {}, {}
|
| 108 |
+
Sents, sentToRef, sentToTokens = {}, {}, {}
|
| 109 |
+
for ref in self.data["refs"]:
|
| 110 |
+
# ids
|
| 111 |
+
ref_id = ref["ref_id"]
|
| 112 |
+
ann_id = ref["ann_id"]
|
| 113 |
+
category_id = ref["category_id"]
|
| 114 |
+
image_id = ref["image_id"]
|
| 115 |
+
|
| 116 |
+
# add mapping related to ref
|
| 117 |
+
Refs[ref_id] = ref
|
| 118 |
+
imgToRefs[image_id] = imgToRefs.get(image_id, []) + [ref]
|
| 119 |
+
catToRefs[category_id] = catToRefs.get(category_id, []) + [ref]
|
| 120 |
+
refToAnn[ref_id] = Anns[ann_id]
|
| 121 |
+
annToRef[ann_id] = ref
|
| 122 |
+
|
| 123 |
+
# add mapping of sent
|
| 124 |
+
for sent in ref["sentences"]:
|
| 125 |
+
Sents[sent["sent_id"]] = sent
|
| 126 |
+
sentToRef[sent["sent_id"]] = ref
|
| 127 |
+
sentToTokens[sent["sent_id"]] = sent["tokens"]
|
| 128 |
+
|
| 129 |
+
# create class members
|
| 130 |
+
self.Refs = Refs
|
| 131 |
+
self.Anns = Anns
|
| 132 |
+
self.Imgs = Imgs
|
| 133 |
+
self.Cats = Cats
|
| 134 |
+
self.Sents = Sents
|
| 135 |
+
self.imgToRefs = imgToRefs
|
| 136 |
+
self.imgToAnns = imgToAnns
|
| 137 |
+
self.refToAnn = refToAnn
|
| 138 |
+
self.annToRef = annToRef
|
| 139 |
+
self.catToRefs = catToRefs
|
| 140 |
+
self.sentToRef = sentToRef
|
| 141 |
+
self.sentToTokens = sentToTokens
|
| 142 |
+
print("index created.")
|
| 143 |
+
|
| 144 |
+
def getRefIds(self, image_ids=[], cat_ids=[], ref_ids=[], split=""):
|
| 145 |
+
image_ids = image_ids if type(image_ids) == list else [image_ids]
|
| 146 |
+
cat_ids = cat_ids if type(cat_ids) == list else [cat_ids]
|
| 147 |
+
ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]
|
| 148 |
+
|
| 149 |
+
if len(image_ids) == len(cat_ids) == len(ref_ids) == len(split) == 0:
|
| 150 |
+
refs = self.data["refs"]
|
| 151 |
+
else:
|
| 152 |
+
if not len(image_ids) == 0:
|
| 153 |
+
refs = [self.imgToRefs[image_id] for image_id in image_ids]
|
| 154 |
+
else:
|
| 155 |
+
refs = self.data["refs"]
|
| 156 |
+
if not len(cat_ids) == 0:
|
| 157 |
+
refs = [ref for ref in refs if ref["category_id"] in cat_ids]
|
| 158 |
+
if not len(ref_ids) == 0:
|
| 159 |
+
refs = [ref for ref in refs if ref["ref_id"] in ref_ids]
|
| 160 |
+
if not len(split) == 0:
|
| 161 |
+
if split in ["testA", "testB", "testC"]:
|
| 162 |
+
refs = [
|
| 163 |
+
ref for ref in refs if split[-1] in ref["split"]
|
| 164 |
+
] # we also consider testAB, testBC, ...
|
| 165 |
+
elif split in ["testAB", "testBC", "testAC"]:
|
| 166 |
+
refs = [
|
| 167 |
+
ref for ref in refs if ref["split"] == split
|
| 168 |
+
] # rarely used I guess...
|
| 169 |
+
elif split == "test":
|
| 170 |
+
refs = [ref for ref in refs if "test" in ref["split"]]
|
| 171 |
+
elif split == "train" or split == "val":
|
| 172 |
+
refs = [ref for ref in refs if ref["split"] == split]
|
| 173 |
+
else:
|
| 174 |
+
print("No such split [%s]" % split)
|
| 175 |
+
sys.exit()
|
| 176 |
+
ref_ids = [ref["ref_id"] for ref in refs]
|
| 177 |
+
return ref_ids
|
| 178 |
+
|
| 179 |
+
def getAnnIds(self, image_ids=[], cat_ids=[], ref_ids=[]):
|
| 180 |
+
image_ids = image_ids if type(image_ids) == list else [image_ids]
|
| 181 |
+
cat_ids = cat_ids if type(cat_ids) == list else [cat_ids]
|
| 182 |
+
ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]
|
| 183 |
+
|
| 184 |
+
if len(image_ids) == len(cat_ids) == len(ref_ids) == 0:
|
| 185 |
+
ann_ids = [ann["id"] for ann in self.data["annotations"]]
|
| 186 |
+
else:
|
| 187 |
+
if not len(image_ids) == 0:
|
| 188 |
+
lists = [
|
| 189 |
+
self.imgToAnns[image_id]
|
| 190 |
+
for image_id in image_ids
|
| 191 |
+
if image_id in self.imgToAnns
|
| 192 |
+
] # list of [anns]
|
| 193 |
+
anns = list(itertools.chain.from_iterable(lists))
|
| 194 |
+
else:
|
| 195 |
+
anns = self.data["annotations"]
|
| 196 |
+
if not len(cat_ids) == 0:
|
| 197 |
+
anns = [ann for ann in anns if ann["category_id"] in cat_ids]
|
| 198 |
+
ann_ids = [ann["id"] for ann in anns]
|
| 199 |
+
if not len(ref_ids) == 0:
|
| 200 |
+
ids = set(ann_ids).intersection(
|
| 201 |
+
set([self.Refs[ref_id]["ann_id"] for ref_id in ref_ids])
|
| 202 |
+
)
|
| 203 |
+
return ann_ids
|
| 204 |
+
|
| 205 |
+
def getImgIds(self, ref_ids=[]):
|
| 206 |
+
ref_ids = ref_ids if type(ref_ids) == list else [ref_ids]
|
| 207 |
+
|
| 208 |
+
if not len(ref_ids) == 0:
|
| 209 |
+
image_ids = list(set([self.Refs[ref_id]["image_id"] for ref_id in ref_ids]))
|
| 210 |
+
else:
|
| 211 |
+
image_ids = self.Imgs.keys()
|
| 212 |
+
return image_ids
|
| 213 |
+
|
| 214 |
+
def getCatIds(self):
|
| 215 |
+
return self.Cats.keys()
|
| 216 |
+
|
| 217 |
+
def loadRefs(self, ref_ids=[]):
|
| 218 |
+
if type(ref_ids) == list:
|
| 219 |
+
return [self.Refs[ref_id] for ref_id in ref_ids]
|
| 220 |
+
elif type(ref_ids) == int:
|
| 221 |
+
return [self.Refs[ref_ids]]
|
| 222 |
+
|
| 223 |
+
def loadAnns(self, ann_ids=[]):
|
| 224 |
+
if type(ann_ids) == list:
|
| 225 |
+
return [self.Anns[ann_id] for ann_id in ann_ids]
|
| 226 |
+
elif type(ann_ids) == int or type(ann_ids) == unicode:
|
| 227 |
+
return [self.Anns[ann_ids]]
|
| 228 |
+
|
| 229 |
+
def loadImgs(self, image_ids=[]):
|
| 230 |
+
if type(image_ids) == list:
|
| 231 |
+
return [self.Imgs[image_id] for image_id in image_ids]
|
| 232 |
+
elif type(image_ids) == int:
|
| 233 |
+
return [self.Imgs[image_ids]]
|
| 234 |
+
|
| 235 |
+
def loadCats(self, cat_ids=[]):
|
| 236 |
+
if type(cat_ids) == list:
|
| 237 |
+
return [self.Cats[cat_id] for cat_id in cat_ids]
|
| 238 |
+
elif type(cat_ids) == int:
|
| 239 |
+
return [self.Cats[cat_ids]]
|
| 240 |
+
|
| 241 |
+
def getRefBox(self, ref_id):
|
| 242 |
+
ref = self.Refs[ref_id]
|
| 243 |
+
ann = self.refToAnn[ref_id]
|
| 244 |
+
return ann["bbox"] # [x, y, w, h]
|
| 245 |
+
|
| 246 |
+
def showRef(self, ref, seg_box="seg"):
|
| 247 |
+
ax = plt.gca()
|
| 248 |
+
# show image
|
| 249 |
+
image = self.Imgs[ref["image_id"]]
|
| 250 |
+
I = io.imread(osp.join(self.IMAGE_DIR, image["file_name"]))
|
| 251 |
+
ax.imshow(I)
|
| 252 |
+
# show refer expression
|
| 253 |
+
for sid, sent in enumerate(ref["sentences"]):
|
| 254 |
+
print("%s. %s" % (sid + 1, sent["sent"]))
|
| 255 |
+
# show segmentations
|
| 256 |
+
if seg_box == "seg":
|
| 257 |
+
ann_id = ref["ann_id"]
|
| 258 |
+
ann = self.Anns[ann_id]
|
| 259 |
+
polygons = []
|
| 260 |
+
color = []
|
| 261 |
+
c = "none"
|
| 262 |
+
if type(ann["segmentation"][0]) == list:
|
| 263 |
+
# polygon used for refcoco*
|
| 264 |
+
for seg in ann["segmentation"]:
|
| 265 |
+
poly = np.array(seg).reshape((len(seg) / 2, 2))
|
| 266 |
+
polygons.append(Polygon(poly, True, alpha=0.4))
|
| 267 |
+
color.append(c)
|
| 268 |
+
p = PatchCollection(
|
| 269 |
+
polygons,
|
| 270 |
+
facecolors=color,
|
| 271 |
+
edgecolors=(1, 1, 0, 0),
|
| 272 |
+
linewidths=3,
|
| 273 |
+
alpha=1,
|
| 274 |
+
)
|
| 275 |
+
ax.add_collection(p) # thick yellow polygon
|
| 276 |
+
p = PatchCollection(
|
| 277 |
+
polygons,
|
| 278 |
+
facecolors=color,
|
| 279 |
+
edgecolors=(1, 0, 0, 0),
|
| 280 |
+
linewidths=1,
|
| 281 |
+
alpha=1,
|
| 282 |
+
)
|
| 283 |
+
ax.add_collection(p) # thin red polygon
|
| 284 |
+
else:
|
| 285 |
+
# mask used for refclef
|
| 286 |
+
rle = ann["segmentation"]
|
| 287 |
+
m = mask.decode(rle)
|
| 288 |
+
img = np.ones((m.shape[0], m.shape[1], 3))
|
| 289 |
+
color_mask = np.array([2.0, 166.0, 101.0]) / 255
|
| 290 |
+
for i in range(3):
|
| 291 |
+
img[:, :, i] = color_mask[i]
|
| 292 |
+
ax.imshow(np.dstack((img, m * 0.5)))
|
| 293 |
+
# show bounding-box
|
| 294 |
+
elif seg_box == "box":
|
| 295 |
+
ann_id = ref["ann_id"]
|
| 296 |
+
ann = self.Anns[ann_id]
|
| 297 |
+
bbox = self.getRefBox(ref["ref_id"])
|
| 298 |
+
box_plot = Rectangle(
|
| 299 |
+
(bbox[0], bbox[1]),
|
| 300 |
+
bbox[2],
|
| 301 |
+
bbox[3],
|
| 302 |
+
fill=False,
|
| 303 |
+
edgecolor="green",
|
| 304 |
+
linewidth=3,
|
| 305 |
+
)
|
| 306 |
+
ax.add_patch(box_plot)
|
| 307 |
+
|
| 308 |
+
def getMask(self, ref):
|
| 309 |
+
# return mask, area and mask-center
|
| 310 |
+
ann = self.refToAnn[ref["ref_id"]]
|
| 311 |
+
image = self.Imgs[ref["image_id"]]
|
| 312 |
+
if type(ann["segmentation"][0]) == list: # polygon
|
| 313 |
+
rle = mask.frPyObjects(ann["segmentation"], image["height"], image["width"])
|
| 314 |
+
else:
|
| 315 |
+
rle = ann["segmentation"]
|
| 316 |
+
m = mask.decode(rle)
|
| 317 |
+
m = np.sum(
|
| 318 |
+
m, axis=2
|
| 319 |
+
) # sometimes there are multiple binary map (corresponding to multiple segs)
|
| 320 |
+
m = m.astype(np.uint8) # convert to np.uint8
|
| 321 |
+
# compute area
|
| 322 |
+
area = sum(mask.area(rle)) # should be close to ann['area']
|
| 323 |
+
return {"mask": m, "area": area}
|
| 324 |
+
# # position
|
| 325 |
+
# position_x = np.mean(np.where(m==1)[1]) # [1] means columns (matlab style) -> x (c style)
|
| 326 |
+
# position_y = np.mean(np.where(m==1)[0]) # [0] means rows (matlab style) -> y (c style)
|
| 327 |
+
# # mass position (if there were multiple regions, we use the largest one.)
|
| 328 |
+
# label_m = label(m, connectivity=m.ndim)
|
| 329 |
+
# regions = regionprops(label_m)
|
| 330 |
+
# if len(regions) > 0:
|
| 331 |
+
# largest_id = np.argmax(np.array([props.filled_area for props in regions]))
|
| 332 |
+
# largest_props = regions[largest_id]
|
| 333 |
+
# mass_y, mass_x = largest_props.centroid
|
| 334 |
+
# else:
|
| 335 |
+
# mass_x, mass_y = position_x, position_y
|
| 336 |
+
# # if centroid is not in mask, we find the closest point to it from mask
|
| 337 |
+
# if m[mass_y, mass_x] != 1:
|
| 338 |
+
# print('Finding closes mask point ...')
|
| 339 |
+
# kernel = np.ones((10, 10),np.uint8)
|
| 340 |
+
# me = cv2.erode(m, kernel, iterations = 1)
|
| 341 |
+
# points = zip(np.where(me == 1)[0].tolist(), np.where(me == 1)[1].tolist()) # row, col style
|
| 342 |
+
# points = np.array(points)
|
| 343 |
+
# dist = np.sum((points - (mass_y, mass_x))**2, axis=1)
|
| 344 |
+
# id = np.argsort(dist)[0]
|
| 345 |
+
# mass_y, mass_x = points[id]
|
| 346 |
+
# # return
|
| 347 |
+
# return {'mask': m, 'area': area, 'position_x': position_x, 'position_y': position_y, 'mass_x': mass_x, 'mass_y': mass_y}
|
| 348 |
+
# # show image and mask
|
| 349 |
+
# I = io.imread(osp.join(self.IMAGE_DIR, image['file_name']))
|
| 350 |
+
# plt.figure()
|
| 351 |
+
# plt.imshow(I)
|
| 352 |
+
# ax = plt.gca()
|
| 353 |
+
# img = np.ones( (m.shape[0], m.shape[1], 3) )
|
| 354 |
+
# color_mask = np.array([2.0,166.0,101.0])/255
|
| 355 |
+
# for i in range(3):
|
| 356 |
+
# img[:,:,i] = color_mask[i]
|
| 357 |
+
# ax.imshow(np.dstack( (img, m*0.5) ))
|
| 358 |
+
# plt.show()
|
| 359 |
+
|
| 360 |
+
def showMask(self, ref):
|
| 361 |
+
M = self.getMask(ref)
|
| 362 |
+
msk = M["mask"]
|
| 363 |
+
ax = plt.gca()
|
| 364 |
+
ax.imshow(msk)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
if __name__ == "__main__":
|
| 368 |
+
refer = REFER(dataset="refcocog", splitBy="google")
|
| 369 |
+
ref_ids = refer.getRefIds()
|
| 370 |
+
print(len(ref_ids))
|
| 371 |
+
|
| 372 |
+
print(len(refer.Imgs))
|
| 373 |
+
print(len(refer.imgToRefs))
|
| 374 |
+
|
| 375 |
+
ref_ids = refer.getRefIds(split="train")
|
| 376 |
+
print("There are %s training referred objects." % len(ref_ids))
|
| 377 |
+
|
| 378 |
+
for ref_id in ref_ids:
|
| 379 |
+
ref = refer.loadRefs(ref_id)[0]
|
| 380 |
+
if len(ref["sentences"]) < 2:
|
| 381 |
+
continue
|
| 382 |
+
|
| 383 |
+
pprint(ref)
|
| 384 |
+
print("The label is %s." % refer.Cats[ref["category_id"]])
|
| 385 |
+
plt.figure()
|
| 386 |
+
refer.showRef(ref, seg_box="box")
|
| 387 |
+
plt.show()
|
| 388 |
+
|
| 389 |
+
# plt.figure()
|
| 390 |
+
# refer.showMask(ref)
|
| 391 |
+
# plt.show()
|