2020-09-18 15:49:13 +00:00
|
|
|
import os.path as osp
|
|
|
|
from data import util
|
|
|
|
import torch
|
2020-09-25 22:37:54 +00:00
|
|
|
import numpy as np
|
2020-09-18 15:49:13 +00:00
|
|
|
|
|
|
|
# Iterable that reads all the images in a directory that contains a reference image, tile images and center coordinates.
|
|
|
|
class ChunkWithReference:
|
|
|
|
def __init__(self, opt, path):
|
2020-09-25 22:37:54 +00:00
|
|
|
self.path = path.path
|
2020-09-26 04:45:57 +00:00
|
|
|
self.tiles, _ = util.get_image_paths('img', self.path)
|
2020-10-18 02:09:08 +00:00
|
|
|
self.strict = opt['strict'] if 'strict' in opt.keys() else True
|
2020-10-17 15:45:03 +00:00
|
|
|
if 'ignore_first' in opt.keys():
|
|
|
|
self.ignore = opt['ignore_first']
|
|
|
|
self.tiles = self.tiles[self.ignore:]
|
|
|
|
else:
|
|
|
|
self.ignore = 0
|
2020-09-26 04:19:38 +00:00
|
|
|
|
2020-10-11 14:33:18 +00:00
|
|
|
# Odd failures occur at times. Rather than crashing, report the error and just return zeros.
|
|
|
|
def read_image_or_get_zero(self, img_path):
|
|
|
|
img = util.read_img(None, img_path, rgb=True)
|
|
|
|
if img is None:
|
|
|
|
return np.zeros(128, 128, 3)
|
2020-10-12 16:23:03 +00:00
|
|
|
return img
|
2020-10-11 14:33:18 +00:00
|
|
|
|
2020-09-18 15:49:13 +00:00
|
|
|
def __getitem__(self, item):
|
2020-10-11 14:33:18 +00:00
|
|
|
tile = self.read_image_or_get_zero(self.tiles[item])
|
2020-10-26 17:12:22 +00:00
|
|
|
if osp.exists(osp.join(self.path, "ref.jpg")):
|
|
|
|
tile_id = int(osp.splitext(osp.basename(self.tiles[item]))[0])
|
|
|
|
centers = torch.load(osp.join(self.path, "centers.pt"))
|
|
|
|
ref = self.read_image_or_get_zero(osp.join(self.path, "ref.jpg"))
|
|
|
|
if tile_id in centers.keys():
|
|
|
|
center, tile_width = centers[tile_id]
|
|
|
|
elif self.strict:
|
|
|
|
raise FileNotFoundError(tile_id, self.tiles[item])
|
|
|
|
else:
|
|
|
|
center = torch.tensor([128, 128], dtype=torch.long)
|
|
|
|
tile_width = 256
|
|
|
|
mask = np.full(tile.shape[:2] + (1,), fill_value=.1, dtype=tile.dtype)
|
|
|
|
mask[center[0] - tile_width // 2:center[0] + tile_width // 2, center[1] - tile_width // 2:center[1] + tile_width // 2] = 1
|
2020-10-18 02:09:08 +00:00
|
|
|
else:
|
2020-10-26 17:12:22 +00:00
|
|
|
ref = np.zeros_like(tile)
|
|
|
|
mask = np.zeros(tile.shape[:2] + (1,))
|
|
|
|
center = (0,0)
|
2020-09-18 15:49:13 +00:00
|
|
|
|
2020-09-25 22:37:54 +00:00
|
|
|
return tile, ref, center, mask, self.tiles[item]
|
2020-09-18 15:49:13 +00:00
|
|
|
|
|
|
|
def __len__(self):
|
2020-09-25 22:37:54 +00:00
|
|
|
return len(self.tiles)
|