File size: 1,747 Bytes
f66a12f | 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 | """Read raw pixel annotations; no coordinate quantization or target formatting."""
import base64
import io
import json
from pathlib import Path
from PIL import Image
class RawTSVDataset:
def __init__(self, root, positive_only=False):
self.root = Path(root)
self.manifest = json.loads((self.root/'manifest.json').read_text())
name = 'train.positive.annotations.tsv.lineidx' if positive_only else 'train.annotations.tsv.lineidx'
self.offsets = [int(x) for x in (self.root/name).read_text().splitlines()]
def __len__(self):
return len(self.offsets)
def __getitem__(self, index):
# Open per request: safe under fork/spawn and concurrent readers.
with (self.root/'train.annotations.tsv').open('rb') as f:
f.seek(self.offsets[index])
offset, payload = f.readline().split(b'\t', 1)
annotation = json.loads(payload)
with (self.root/'train.images.tsv').open('rb') as f:
f.seek(int(offset))
key, encoded = f.readline().rstrip(b'\n').split(b'\t', 1)
if int(key) != int(offset):
raise ValueError('Image offset mismatch')
data = base64.b64decode(encoded, validate=True)
return {'image_bytes': data, 'annotation': annotation}
@staticmethod
def decode(sample):
# Do not EXIF-transpose: all coordinates describe the stored raster.
with Image.open(io.BytesIO(sample['image_bytes'])) as source:
image = source.convert('RGB')
image.info.pop('exif', None)
ann = sample['annotation']
if image.size != (ann['width'], ann['height']):
raise ValueError('Image size mismatch')
return {'image': image, 'annotation': ann}
|