1#!/usr/bin/env python
2# coding=utf-8
3
4
5"""Data loading code"""
6
7
8import os
9import functools
10
11import PIL.Image
12
13from .sample import DelayedSample
14
15
16def load_pil(path):
17 """Loads a sample data
18
19 Parameters
20 ----------
21
22 path : str
23 The full path leading to the image to be loaded
24
25
26 Returns
27 -------
28
29 image : PIL.Image.Image
30 A PIL image
31
32 """
33
34 return PIL.Image.open(path)
35
36
37def load_pil_baw(path):
38 """Loads a sample data
39
40 Parameters
41 ----------
42
43 path : str
44 The full path leading to the image to be loaded
45
46
47 Returns
48 -------
49
50 image : PIL.Image.Image
51 A PIL image in grayscale mode
52
53 """
54
55 return load_pil(path).convert("L")
56
57
58def load_pil_rgb(path):
59 """Loads a sample data
60
61 Parameters
62 ----------
63
64 path : str
65 The full path leading to the image to be loaded
66
67
68 Returns
69 -------
70
71 image : PIL.Image.Image
72 A PIL image in RGB mode
73
74 """
75
76 return load_pil(path).convert("RGB")
77
78
79def make_delayed(sample, loader, key=None):
80 """Returns a delayed-loading Sample object
81
82 Parameters
83 ----------
84
85 sample : dict
86 A dictionary that maps field names to sample data values (e.g. paths)
87
88 loader : object
89 A function that inputs ``sample`` dictionaries and returns the loaded
90 data.
91
92 key : str
93 A unique key identifier for this sample. If not provided, assumes
94 ``sample`` is a dictionary with a ``data`` entry and uses its path as
95 key.
96
97
98 Returns
99 -------
100
101 sample : bob.med.tb.data.sample.DelayedSample
102 In which ``key`` is as provided and ``data`` can be accessed to trigger
103 sample loading.
104
105 """
106
107 return DelayedSample(
108 functools.partial(loader, sample),
109 key=key or sample["data"],
110 label=sample["label"]
111 )