def __getitem__(self, idx): img_path, gt = self.lines[idx] img = cv2.imread(img_path, 0) if img is None: return None if img.shape[0] != self.img_height: if img.shape[0] < self.img_height and not self.warning: self.warning = True print("WARNING: upsampling image to fit size") percent = float(self.img_height) / img.shape[0] img = cv2.resize(img, (0, 0), fx=percent, fy=percent, interpolation=cv2.INTER_CUBIC) if img is None: return None if self.augmentation: img = augmentation.apply_random_color_rotation(img) img = augmentation.apply_tensmeyer_brightness(img) img = grid_distortion.warp_image(img) img = img.astype(np.float32) img = img / 128.0 - 1.0 img = img[..., None] if len(gt) == 0: return None gt_label = string_utils.str2label_single(gt, self.char_to_idx) return {"line_img": img, "gt": gt, "gt_label": gt_label}
def __getitem__(self, idx): gt_json_path, img_path = self.ids[idx] gt_json = safe_load.json_state(gt_json_path) if gt_json is None: return None # print('img_path: {}'.format(img_path)) org_img = cv2.imread(img_path, cv2.IMREAD_COLOR) # print('img.size: {}'.format(org_img.shape)) # median = np.median(org_img, axis=(0,1)) # org_img = cv2.copyMakeBorder(org_img,100,100,100,100,cv2.BORDER_CONSTANT,value=median) target_dim1 = int(np.random.uniform(self.rescale_range[0], self.rescale_range[1])) s = target_dim1 / float(org_img.shape[1]) target_dim0 = int(org_img.shape[0]/float(org_img.shape[1]) * target_dim1) org_img = cv2.resize(org_img,(target_dim1, target_dim0), interpolation = cv2.INTER_CUBIC) gt = np.zeros((1,len(gt_json['corners']), 4), dtype=np.float32) for j, gt_item in enumerate(gt_json['corners']): x0 = gt_item[0] x1 = gt_item[0] y0 = gt_item[1] y1 = gt_item[1] gt[:,j,0] = x0 * s gt[:,j,1] = y0 * s gt[:,j,2] = x1 * s gt[:,j,3] = y1 * s if self.transform is not None: out = self.transform({ "img": org_img, "sol_gt": gt }) org_img = out['img'] gt = out['sol_gt'] org_img = augmentation.apply_random_color_rotation(org_img) org_img = augmentation.apply_tensmeyer_brightness(org_img) org_img = augmentation.apply_random_blur(org_img) img = org_img.transpose([2,1,0])[None,...] img = img.astype(np.float32) img = torch.from_numpy(img) img = img / 128.0 - 1.0 if gt.shape[1] == 0: gt = None else: gt = torch.from_numpy(gt) return { "img": img, "sol_gt": gt }
def __getitem__(self, idx): gt_json_path, img_path = self.ids[idx] gt_json = safe_load.json_state(gt_json_path) if gt_json is None: return None org_img = cv2.imread(img_path) target_dim1 = int(np.random.uniform(self.rescale_range[0], self.rescale_range[1])) s = target_dim1 / float(org_img.shape[1]) target_dim0 = int(org_img.shape[0]/float(org_img.shape[1]) * target_dim1) org_img = cv2.resize(org_img,(target_dim1, target_dim0), interpolation = cv2.INTER_CUBIC) gt = np.zeros((1,len(gt_json), 4), dtype=np.float32) for j, gt_item in enumerate(gt_json): if 'sol' not in gt_item: continue x0 = gt_item['sol']['x0'] x1 = gt_item['sol']['x1'] y0 = gt_item['sol']['y0'] y1 = gt_item['sol']['y1'] gt[:,j,0] = x0 * s gt[:,j,1] = y0 * s gt[:,j,2] = x1 * s gt[:,j,3] = y1 * s if self.transform is not None: out = self.transform({ "img": org_img, "sol_gt": gt }) org_img = out['img'] gt = out['sol_gt'] org_img = augmentation.apply_random_color_rotation(org_img) org_img = augmentation.apply_tensmeyer_brightness(org_img) img = org_img.transpose([2,1,0])[None,...] img = img.astype(np.float32) img = torch.from_numpy(img) img = img / 128.0 - 1.0 if gt.shape[1] == 0: gt = None else: gt = torch.from_numpy(gt) return { "img": img, "sol_gt": gt }
def __getitem__(self, idx): ids_idx, line_idx = self.detailed_ids[idx] gt_json_path, img_path = self.ids[ids_idx] gt_json = safe_load.json_state(gt_json_path) positions = [] positions_xy = [] if 'lf' not in gt_json[line_idx]: return None for step in gt_json[line_idx]['lf']: x0 = step['x0'] x1 = step['x1'] y0 = step['y0'] y1 = step['y1'] positions_xy.append((torch.Tensor([[x1, x0], [y1, y0]]))) dx = x0 - x1 dy = y0 - y1 d = math.sqrt(dx**2 + dy**2) mx = (x0 + x1) / 2.0 my = (y0 + y1) / 2.0 #Not sure if this is right... theta = -math.atan2(dx, -dy) positions.append(torch.Tensor([mx, my, theta, d / 2, 1.0])) img = cv2.imread(img_path) if self.augmentation: img = augmentation.apply_random_color_rotation(img) img = augmentation.apply_tensmeyer_brightness(img) img = img.astype(np.float32) img = img.transpose() img = img / 128.0 - 1.0 img = torch.from_numpy(img) gt = gt_json[line_idx]['gt'] result = { "img": img, "lf_xyrs": positions, "lf_xyxy": positions_xy, "gt": gt } return result
def __getitem__(self, idx): ids_idx, line_idx = self.detailed_ids[idx] gt_json_path, img_path = self.ids[ids_idx] gt_json = safe_load.json_state(gt_json_path) if gt_json is None: return None if 'hw_path' not in gt_json[line_idx]: return None hw_path = gt_json[line_idx]['hw_path'] hw_path = hw_path.split("/")[-1:] hw_path = "/".join(hw_path) hw_folder = os.path.dirname(gt_json_path) img = cv2.imread(os.path.join(hw_folder, hw_path)) if img is None: return None if img.shape[0] != self.img_height: if img.shape[0] < self.img_height and not self.warning: self.warning = True print "WARNING: upsampling image to fit size" percent = float(self.img_height) / img.shape[0] img = cv2.resize(img, (0,0), fx=percent, fy=percent, interpolation = cv2.INTER_CUBIC) if img is None: return None if self.augmentation: img = augmentation.apply_random_color_rotation(img) img = augmentation.apply_tensmeyer_brightness(img) img = grid_distortion.warp_image(img) img = img.astype(np.float32) img = img / 128.0 - 1.0 gt = gt_json[line_idx]['gt'] if len(gt) == 0: return None gt_label = string_utils.str2label_single(gt, self.char_to_idx) return { "line_img": img, "gt": gt, "gt_label": gt_label }
def getitem(self, index, scaleP=None, cropPoint=None): if self.useRandomAugProb is not None and np.random.rand( ) < self.useRandomAugProb and scaleP is None and cropPoint is None: return self.getRandomImage() ##ticFull=timeit.default_timer() imagePath = self.images[index]['imagePath'] imageName = self.images[index]['imageName'] annotationPath = self.images[index]['annotationPath'] #print(annotationPath) rescaled = self.images[index]['rescaled'] with open(annotationPath) as annFile: annotations = json.loads(annFile.read()) ##tic=timeit.default_timer() np_img = cv2.imread(imagePath, 1 if self.color else 0) #/255.0 if np_img is None or np_img.shape[0] == 0: print("ERROR, could not open " + imagePath) return self.__getitem__((index + 1) % self.__len__()) if scaleP is None: s = np.random.uniform(self.rescale_range[0], self.rescale_range[1]) else: s = scaleP partial_rescale = s / rescaled if self.transform is None: #we're doing the whole image #this is a check to be sure we don't send too big images through pixel_count = partial_rescale * partial_rescale * np_img.shape[ 0] * np_img.shape[1] if pixel_count > self.pixel_count_thresh: partial_rescale = math.sqrt(partial_rescale * partial_rescale * self.pixel_count_thresh / pixel_count) print('{} exceed thresh: {}: {}, new {}: {}'.format( imageName, s, pixel_count, rescaled * partial_rescale, partial_rescale * partial_rescale * np_img.shape[0] * np_img.shape[1])) s = rescaled * partial_rescale max_dim = partial_rescale * max(np_img.shape[0], np_img.shape[1]) if max_dim > self.max_dim_thresh: partial_rescale = partial_rescale * (self.max_dim_thresh / max_dim) print('{} exceed thresh: {}: {}, new {}: {}'.format( imageName, s, max_dim, rescaled * partial_rescale, partial_rescale * max(np_img.shape[0], np_img.shape[1]))) s = rescaled * partial_rescale ##tic=timeit.default_timer() #np_img = cv2.resize(np_img,(target_dim1, target_dim0), interpolation = cv2.INTER_CUBIC) np_img = cv2.resize(np_img, (0, 0), fx=partial_rescale, fy=partial_rescale, interpolation=cv2.INTER_CUBIC) if not self.color: np_img = np_img[..., None] #add 'color' channel ##print('resize: {} [{}, {}]'.format(timeit.default_timer()-tic,np_img.shape[0],np_img.shape[1])) bbs, line_gts, point_gts, pixel_gt, numClasses, numNeighbors, pairs = self.parseAnn( np_img, annotations, s, imagePath) if self.coordConv: #add absolute position information xs = 255 * np.arange(np_img.shape[1]) / (np_img.shape[1]) xs = np.repeat(xs[None, :, None], np_img.shape[0], axis=0) ys = 255 * np.arange(np_img.shape[0]) / (np_img.shape[0]) ys = np.repeat(ys[:, None, None], np_img.shape[1], axis=1) np_img = np.concatenate( (np_img, xs.astype(np_img.dtype), ys.astype(np_img.dtype)), axis=2) ##ticTr=timeit.default_timer() if self.transform is not None: pairs = None out, cropPoint = self.transform( { "img": np_img, "bb_gt": bbs, "bb_auxs": numNeighbors, "line_gt": line_gts, "point_gt": point_gts, "pixel_gt": pixel_gt, }, cropPoint) np_img = out['img'] bbs = out['bb_gt'] numNeighbors = out['bb_auxs'] #if 'table_points' in out['point_gt']: # table_points = out['point_gt']['table_points'] #else: # table_points=None point_gts = out['point_gt'] pixel_gt = out['pixel_gt'] #start_of_line = out['line_gt']['start_of_line'] #end_of_line = out['line_gt']['end_of_line'] line_gts = out['line_gt'] ##tic=timeit.default_timer() if self.color: np_img[:, :, :3] = augmentation.apply_random_color_rotation( np_img[:, :, :3]) np_img[:, :, :3] = augmentation.apply_tensmeyer_brightness( np_img[:, :, :3]) else: np_img[:, :, 0:1] = augmentation.apply_tensmeyer_brightness( np_img[:, :, 0:1]) ##print('augmentation: {}'.format(timeit.default_timer()-tic)) ##print('transfrm: {} [{}, {}]'.format(timeit.default_timer()-ticTr,org_img.shape[0],org_img.shape[1])) #if len(np_img.shape)==2: # img=np_img[None,None,:,:] #add "color" channel and batch #else: img = np_img.transpose( [2, 0, 1])[None, ...] #from [row,col,color] to [batch,color,row,col] img = img.astype(np.float32) img = torch.from_numpy(img) img = 1.0 - img / 128.0 #ideally the median value would be 0 #img = 1.0 - img / 255.0 #this way ink is on, page is off if pixel_gt is not None: pixel_gt = pixel_gt.transpose([2, 0, 1])[None, ...] pixel_gt = torch.from_numpy(pixel_gt) #start_of_line = None if start_of_line is None or start_of_line.shape[1] == 0 else torch.from_numpy(start_of_line) #end_of_line = None if end_of_line is None or end_of_line.shape[1] == 0 else torch.from_numpy(end_of_line) for name in line_gts: line_gts[name] = None if line_gts[name] is None or line_gts[ name].shape[1] == 0 else torch.from_numpy(line_gts[name]) #import pdb; pdb.set_trace() #bbs = None if bbs.shape[1] == 0 else torch.from_numpy(bbs) bbs = convertBBs(bbs, self.rotate, numClasses) if len(numNeighbors) > 0: numNeighbors = torch.tensor(numNeighbors)[None, :] #add batch dim else: numNeighbors = None #start_of_line = convertLines(start_of_line,numClasses) #end_of_line = convertLines(end_of_line,numClasses) for name in point_gts: #if table_points is not None: #table_points = None if table_points.shape[1] == 0 else torch.from_numpy(table_points) if point_gts[name] is not None: point_gts[name] = None if point_gts[name].shape[ 1] == 0 else torch.from_numpy(point_gts[name]) ##print('__getitem__: '+str(timeit.default_timer()-ticFull)) if self.only_types is None: return { "img": img, "bb_gt": bbs, "num_neighbors": numNeighbors, "line_gt": line_gts, "point_gt": point_gts, "pixel_gt": pixel_gt, "imgName": imageName, "scale": s, "cropPoint": cropPoint, "pairs": pairs } else: if 'boxes' not in self.only_types or not self.only_types['boxes']: bbs = None line_gt = {} if 'line' in self.only_types: for ent in self.only_types['line']: if type(ent) == list: toComb = [] for inst in ent[1:]: einst = line_gts[inst] if einst is not None: toComb.append(einst) if len(toComb) > 0: comb = torch.cat(toComb, dim=1) line_gt[ent[0]] = comb else: line_gt[ent[0]] = None else: line_gt[ent] = line_gts[ent] point_gt = {} if 'point' in self.only_types: for ent in self.only_types['point']: if type(ent) == list: toComb = [] for inst in ent[1:]: einst = point_gts[inst] if einst is not None: toComb.append(einst) if len(toComb) > 0: comb = torch.cat(toComb, dim=1) point_gt[ent[0]] = comb else: line_gt[ent[0]] = None else: point_gt[ent] = point_gts[ent] pixel_gtR = None #for ent in self.only_types['pixel']: # if type(ent)==list: # comb = ent[1] # for inst in ent[2:]: # comb = (comb + inst)==2 #:eq(2) #pixel-wise AND # pixel_gt[ent[0]]=comb # else: # pixel_gt[ent]=eval(ent) if 'pixel' in self.only_types: # and self.only_types['pixel'][0]=='table_pixels': pixel_gtR = pixel_gt return { "img": img, "bb_gt": bbs, "num_neighbors": numNeighbors, "line_gt": line_gt, "point_gt": point_gt, "pixel_gt": pixel_gtR, "imgName": imageName, "scale": s, "cropPoint": cropPoint, "pairs": pairs, }
def getitem(self, index, scaleP=None, cropPoint=None): ##ticFull=timeit.default_timer() imagePath = self.images[index]['imagePath'] imageName = self.images[index]['imageName'] annotationPath = self.images[index]['annotationPath'] #print(annotationPath) rescaled = self.images[index]['rescaled'] with open(annotationPath) as annFile: annotations = json.loads(annFile.read()) ##tic=timeit.default_timer() np_img = cv2.imread(imagePath, 1 if self.color else 0) #/255.0 if np_img is None or np_img.shape[0] == 0: print("ERROR, could not open " + imagePath) return self.__getitem__((index + 1) % self.__len__()) if scaleP is None: s = np.random.uniform(self.rescale_range[0], self.rescale_range[1]) else: s = scaleP partial_rescale = s / rescaled if self.transform is None: #we're doing the whole image #this is a check to be sure we don't send too big images through pixel_count = partial_rescale * partial_rescale * np_img.shape[ 0] * np_img.shape[1] if pixel_count > self.pixel_count_thresh: partial_rescale = math.sqrt(partial_rescale * partial_rescale * self.pixel_count_thresh / pixel_count) print('{} exceed thresh: {}: {}, new {}: {}'.format( imageName, s, pixel_count, rescaled * partial_rescale, partial_rescale * partial_rescale * np_img.shape[0] * np_img.shape[1])) s = rescaled * partial_rescale max_dim = partial_rescale * max(np_img.shape[0], np_img.shape[1]) if max_dim > self.max_dim_thresh: partial_rescale = partial_rescale * (self.max_dim_thresh / max_dim) print('{} exceed thresh: {}: {}, new {}: {}'.format( imageName, s, max_dim, rescaled * partial_rescale, partial_rescale * max(np_img.shape[0], np_img.shape[1]))) s = rescaled * partial_rescale ##tic=timeit.default_timer() #np_img = cv2.resize(np_img,(target_dim1, target_dim0), interpolation = cv2.INTER_CUBIC) np_img = cv2.resize(np_img, (0, 0), fx=partial_rescale, fy=partial_rescale, interpolation=cv2.INTER_CUBIC) if not self.color: np_img = np_img[..., None] #add 'color' channel ##print('resize: {} [{}, {}]'.format(timeit.default_timer()-tic,np_img.shape[0],np_img.shape[1])) ##tic=timeit.default_timer() bbs, ids, numClasses, trans = self.parseAnn(annotations, s) #start_of_line, end_of_line = getStartEndGT(annotations['byId'].values(),s) #Try: # table_points, table_pixels = self.getTables( # fieldBBs, # s, # np_img.shape[0], # np_img.shape[1], # annotations['samePairs']) #Except Exception as inst: # if imageName not in self.errors: # table_points=None # table_pixels=None # print(inst) # print('Table error on: '+imagePath) # self.errors.append(imageName) #pixel_gt = table_pixels ##ticTr=timeit.default_timer() if self.transform is not None: out, cropPoint = self.transform( { "img": np_img, "bb_gt": bbs, 'bb_auxs': ids, #"line_gt": { # "start_of_line": start_of_line, # "end_of_line": end_of_line # }, #"point_gt": { # "table_points": table_points # }, #"pixel_gt": pixel_gt, }, cropPoint) np_img = out['img'] bbs = out['bb_gt'] ids = out['bb_auxs'] ##tic=timeit.default_timer() if np_img.shape[2] == 3: np_img = augmentation.apply_random_color_rotation(np_img) np_img = augmentation.apply_tensmeyer_brightness(np_img) else: np_img = augmentation.apply_tensmeyer_brightness(np_img) ##print('augmentation: {}'.format(timeit.default_timer()-tic)) ##print('transfrm: {} [{}, {}]'.format(timeit.default_timer()-ticTr,org_img.shape[0],org_img.shape[1])) pairs = set() #import pdb;pdb.set_trace() numNeighbors = [0] * len(ids) for index1, id in enumerate(ids): #updated responseBBIdList = self.getResponseBBIdList(id, annotations) for bbId in responseBBIdList: try: index2 = ids.index(bbId) #adjMatrix[min(index1,index2),max(index1,index2)]=1 pairs.add((min(index1, index2), max(index1, index2))) numNeighbors[index1] += 1 except ValueError: pass #ones = torch.ones(len(pairs)) #if len(pairs)>0: # pairs = torch.LongTensor(list(pairs)).t() #else: # pairs = torch.LongTensor(pairs) #adjMatrix = torch.sparse.FloatTensor(pairs,ones,(len(ids),len(ids))) # This is an upper diagonal matrix as pairings are bi-directional #if len(np_img.shape)==2: # img=np_img[None,None,:,:] #add "color" channel and batch #else: img = np_img.transpose( [2, 0, 1])[None, ...] #from [row,col,color] to [batch,color,row,col] img = img.astype(np.float32) img = torch.from_numpy(img) img = 1.0 - img / 128.0 #ideally the median value would be 0 #if pixel_gt is not None: # pixel_gt = pixel_gt.transpose([2,0,1])[None,...] # pixel_gt = torch.from_numpy(pixel_gt) #start_of_line = None if start_of_line is None or start_of_line.shape[1] == 0 else torch.from_numpy(start_of_line) #end_of_line = None if end_of_line is None or end_of_line.shape[1] == 0 else torch.from_numpy(end_of_line) bbs = convertBBs(bbs, self.rotate, numClasses) if len(numNeighbors) > 0: numNeighbors = torch.tensor(numNeighbors)[None, :] #add batch dim else: numNeighbors = None #if table_points is not None: # table_points = None if table_points.shape[1] == 0 else torch.from_numpy(table_points) return { "img": img, "bb_gt": bbs, "num_neighbors": numNeighbors, "adj": pairs, #adjMatrix, "imgName": imageName, "scale": s, "cropPoint": cropPoint, "transcription": [trans[id] for id in ids if id in trans] }
def getitem(self, index, scaleP=None, cropPoint=None): ##ticFull=timeit.default_timer() imagePath = self.images[index]['imagePath'] imageName = self.images[index]['imageName'] annotationPath = self.images[index]['annotationPath'] #print(annotationPath) rescaled = self.images[index]['rescaled'] with open(annotationPath) as annFile: annotations = json.loads(annFile.read()) ##tic=timeit.default_timer() np_img = img_f.imread(imagePath, 1 if self.color else 0) #*255.0 if np_img.max() < 200: np_img *= 255 if np_img is None or np_img.shape[0] == 0: print("ERROR, could not open " + imagePath) return self.__getitem__((index + 1) % self.__len__()) if scaleP is None: s = np.random.uniform(self.rescale_range[0], self.rescale_range[1]) else: s = scaleP partial_rescale = s / rescaled if self.transform is None: #we're doing the whole image #this is a check to be sure we don't send too big images through pixel_count = partial_rescale * partial_rescale * np_img.shape[ 0] * np_img.shape[1] if pixel_count > self.pixel_count_thresh: partial_rescale = math.sqrt(partial_rescale * partial_rescale * self.pixel_count_thresh / pixel_count) print('{} exceed thresh: {}: {}, new {}: {}'.format( imageName, s, pixel_count, rescaled * partial_rescale, partial_rescale * partial_rescale * np_img.shape[0] * np_img.shape[1])) s = rescaled * partial_rescale max_dim = partial_rescale * max(np_img.shape[0], np_img.shape[1]) if max_dim > self.max_dim_thresh: partial_rescale = partial_rescale * (self.max_dim_thresh / max_dim) print('{} exceed thresh: {}: {}, new {}: {}'.format( imageName, s, max_dim, rescaled * partial_rescale, partial_rescale * max(np_img.shape[0], np_img.shape[1]))) s = rescaled * partial_rescale ##tic=timeit.default_timer() #np_img = img_f.resize(np_img,(target_dim1, target_dim0)) np_img = img_f.resize( np_img, (0, 0), fx=partial_rescale, fy=partial_rescale, ) if len(np_img.shape) == 2: np_img = np_img[..., None] #add 'color' channel if self.color and np_img.shape[2] == 1: np_img = np.repeat(np_img, 3, axis=2) ##print('resize: {} [{}, {}]'.format(timeit.default_timer()-tic,np_img.shape[0],np_img.shape[1])) ##tic=timeit.default_timer() bbs, ids, numClasses, trans, groups, metadata, form_metadata = self.parseAnn( annotations, s) #trans = {i:v for i,v in enumerate(trans)} #metadata = {i:v for i,v in enumerate(metadata)} #start_of_line, end_of_line = getStartEndGT(annotations['byId'].values(),s) #Try: # table_points, table_pixels = self.getTables( # fieldBBs, # s, # np_img.shape[0], # np_img.shape[1], # annotations['samePairs']) #Except Exception as inst: # if imageName not in self.errors: # table_points=None # table_pixels=None # print(inst) # print('Table error on: '+imagePath) # self.errors.append(imageName) #pixel_gt = table_pixels ##ticTr=timeit.default_timer() if self.questions: #we need to do questions before crop to have full context #we have to relationships to get questions pairs = set() for index1, id in enumerate(ids): #updated responseBBIdList = self.getResponseBBIdList(id, annotations) for bbId in responseBBIdList: try: index2 = ids.index(bbId) pairs.add((min(index1, index2), max(index1, index2))) except ValueError: pass groups_adj = set() if groups is not None: for n0, n1 in pairs: g0 = -1 g1 = -1 for i, ns in enumerate(groups): if n0 in ns: g0 = i if g1 != -1: break if n1 in ns: g1 = i if g0 != -1: break if g0 != g1: groups_adj.add((min(g0, g1), max(g0, g1))) questions_and_answers = self.makeQuestions(bbs, trans, groups, groups_adj) else: questions_and_answers = None if self.transform is not None: if 'word_boxes' in form_metadata: word_bbs = form_metadata['word_boxes'] dif_f = bbs.shape[2] - word_bbs.shape[1] blank = np.zeros([word_bbs.shape[0], dif_f]) prep_word_bbs = np.concatenate([word_bbs, blank], axis=1)[None, ...] crop_bbs = np.concatenate([bbs, prep_word_bbs], axis=1) crop_ids = ids + [ 'word{}'.format(i) for i in range(word_bbs.shape[0]) ] else: crop_bbs = bbs crop_ids = ids out, cropPoint = self.transform( { "img": np_img, "bb_gt": crop_bbs, 'bb_auxs': crop_ids, #'word_bbs':form_metadata['word_boxes'] if 'word_boxes' in form_metadata else None #"line_gt": { # "start_of_line": start_of_line, # "end_of_line": end_of_line # }, #"point_gt": { # "table_points": table_points # }, #"pixel_gt": pixel_gt, }, cropPoint) np_img = out['img'] if 'word_boxes' in form_metadata: saw_word = False word_index = -1 for i, ii in enumerate(out['bb_auxs']): if not saw_word: if type(ii) is str and 'word' in ii: saw_word = True word_index = i else: assert 'word' in ii bbs = out['bb_gt'][:, :word_index] ids = out['bb_auxs'][:word_index] form_metadata['word_boxes'] = out['bb_gt'][0, word_index:, :8] word_ids = out['bb_auxs'][word_index:] form_metadata['word_trans'] = [ form_metadata['word_trans'][int(id[4:])] for id in word_ids ] else: bbs = out['bb_gt'] ids = out['bb_auxs'] if questions_and_answers is not None: questions = [] answers = [] questions_and_answers = [ (q, a, qids) for q, a, qids in questions_and_answers if all((i in ids) for i in qids) ] if questions_and_answers is not None: if len(questions_and_answers) > self.questions: questions_and_answers = random.sample(questions_and_answers, k=self.questions) if len(questions_and_answers) > 0: questions, answers, _ = zip(*questions_and_answers) else: return self.getitem((index + 1) % len(self)) else: questions = answers = None ##tic=timeit.default_timer() if np_img.shape[2] == 3: np_img = augmentation.apply_random_color_rotation(np_img) np_img = augmentation.apply_tensmeyer_brightness( np_img, **self.aug_params) else: np_img = augmentation.apply_tensmeyer_brightness( np_img, **self.aug_params) ##print('augmentation: {}'.format(timeit.default_timer()-tic)) newGroups = [] for group in groups: newGroup = [ids.index(bbId) for bbId in group if bbId in ids] if len(newGroup) > 0: newGroups.append(newGroup) #print(len(newGroups)-1,newGroup) groups = newGroups ##print('transfrm: {} [{}, {}]'.format(timeit.default_timer()-ticTr,org_img.shape[0],org_img.shape[1])) pairs = set() #import pdb;pdb.set_trace() numNeighbors = [0] * len(ids) for index1, id in enumerate(ids): #updated responseBBIdList = self.getResponseBBIdList(id, annotations) for bbId in responseBBIdList: try: index2 = ids.index(bbId) #adjMatrix[min(index1,index2),max(index1,index2)]=1 pairs.add((min(index1, index2), max(index1, index2))) numNeighbors[index1] += 1 except ValueError: pass #ones = torch.ones(len(pairs)) #if len(pairs)>0: # pairs = torch.LongTensor(list(pairs)).t() #else: # pairs = torch.LongTensor(pairs) #adjMatrix = torch.sparse.FloatTensor(pairs,ones,(len(ids),len(ids))) # This is an upper diagonal matrix as pairings are bi-directional #if len(np_img.shape)==2: # img=np_img[None,None,:,:] #add "color" channel and batch #else: img = np_img.transpose( [2, 0, 1])[None, ...] #from [row,col,color] to [batch,color,row,col] img = img.astype(np.float32) img = torch.from_numpy(img) img = 1.0 - img / 128.0 #ideally the median value would be 0 #if pixel_gt is not None: # pixel_gt = pixel_gt.transpose([2,0,1])[None,...] # pixel_gt = torch.from_numpy(pixel_gt) #start_of_line = None if start_of_line is None or start_of_line.shape[1] == 0 else torch.from_numpy(start_of_line) #end_of_line = None if end_of_line is None or end_of_line.shape[1] == 0 else torch.from_numpy(end_of_line) bbs = convertBBs(bbs, self.rotate, numClasses) if 'word_boxes' in form_metadata: form_metadata['word_boxes'] = convertBBs( form_metadata['word_boxes'][None, ...], self.rotate, 0)[0, ...] if len(numNeighbors) > 0: numNeighbors = torch.tensor(numNeighbors)[None, :] #add batch dim else: numNeighbors = None #if table_points is not None: # table_points = None if table_points.shape[1] == 0 else torch.from_numpy(table_points) groups_adj = set() if groups is not None: for n0, n1 in pairs: g0 = -1 g1 = -1 for i, ns in enumerate(groups): if n0 in ns: g0 = i if g1 != -1: break if n1 in ns: g1 = i if g0 != -1: break if g0 != g1: groups_adj.add((min(g0, g1), max(g0, g1))) for group in groups: for i in group: assert (i < bbs.shape[1]) targetIndexToGroup = {} for groupId, bbIds in enumerate(groups): targetIndexToGroup.update({bbId: groupId for bbId in bbIds}) transcription = [trans[id] for id in ids] return { "img": img, "bb_gt": bbs, "num_neighbors": numNeighbors, "adj": pairs, #adjMatrix, "imgName": imageName, "scale": s, "cropPoint": cropPoint, "transcription": transcription, "metadata": [metadata[id] for id in ids if id in metadata], "form_metadata": form_metadata, "gt_groups": groups, "targetIndexToGroup": targetIndexToGroup, "gt_groups_adj": groups_adj, "questions": questions, "answers": answers }
def __getitem__(self, idx): gt_json_path, img_path = self.ids[idx] gt_json = safe_load.json_state(gt_json_path) if gt_json is None: return None org_img = cv2.imread(img_path) target_dim1 = int( np.random.uniform(self.rescale_range[0], self.rescale_range[1])) s = target_dim1 / float(org_img.shape[1]) target_dim0 = int(org_img.shape[0] / float(org_img.shape[1]) * target_dim1) org_img = cv2.resize(org_img, (target_dim1, target_dim0), interpolation=cv2.INTER_CUBIC) gt = np.zeros((1, len(gt_json), 4), dtype=np.float32) positions = [] positions_xy = [] for j, gt_item in enumerate(gt_json): if 'sol' not in gt_item: continue x0 = gt_item['sol']['x0'] * s x1 = gt_item['sol']['x1'] * s y0 = gt_item['sol']['y0'] * s y1 = gt_item['sol']['y1'] * s positions_xy.append([(torch.Tensor([[x1, x0], [y1, y0]]))]) dx = x0 - x1 dy = y0 - y1 d = math.sqrt(dx**2 + dy**2) mx = (x0 + x1) / 2.0 my = (y0 + y1) / 2.0 # Not sure if this is right... theta = -math.atan2(dx, -dy) positions.append([torch.Tensor([mx, my, theta, d / 2, 1.0])]) gt[:, j, 0] = x0 gt[:, j, 1] = y0 gt[:, j, 2] = x1 gt[:, j, 3] = y1 if self.transform is not None: out = self.transform({"img": org_img, "sol_gt": gt}) org_img = out['img'] gt = out['sol_gt'] org_img = augmentation.apply_random_color_rotation(org_img) org_img = augmentation.apply_tensmeyer_brightness(org_img) img = org_img.transpose([2, 1, 0])[None, ...] img = img.astype(np.float32) img = torch.from_numpy(img) img = img / 128.0 - 1.0 if gt.shape[1] == 0: gt = None else: gt = torch.from_numpy(gt) return { "scale": s, "img_path": img_path, "img": img, "sol_gt": gt, "lf_xyrs": positions, "lf_xyxy": positions_xy, }