-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathdataset.py
More file actions
2290 lines (1989 loc) · 87.5 KB
/
dataset.py
File metadata and controls
2290 lines (1989 loc) · 87.5 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# #############################################################################
# dataset.py
# =================
# Authors :
# Yohann PERRON [yohann.perron@gmail.com]
# Eric BEZZAM [ebezzam@gmail.com]
# #############################################################################
from hydra.utils import get_original_cwd
import numpy as np
import glob
import os
import torch
from abc import abstractmethod
from torch.utils.data import Dataset, Subset
from torchvision import datasets, transforms
from torchvision.transforms import functional as F
from lensless.hardware.trainable_mask import prep_trainable_mask, AdafruitLCD
from lensless.utils.simulation import FarFieldSimulator
from lensless.utils.io import load_image, load_psf, save_image
from lensless.utils.image import is_grayscale, resize, rgb2gray
import re
from lensless.hardware.utils import capture
from lensless.hardware.utils import display
from lensless.hardware.slm import set_programmable_mask, adafruit_sub2full
from datasets import load_dataset
from lensless.recon.rfft_convolve import RealFFTConvolve2D
from huggingface_hub import hf_hub_download
import cv2
from lensless.hardware.sensor import sensor_dict, SensorParam
from scipy.ndimage import rotate
import warnings
from waveprop.noise import add_shot_noise
from lensless.utils.image import shift_with_pad
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in re.split("([0-9]+)", key)]
def natural_sort(arr):
return sorted(arr, key=alphanum_key)
# available datasets
available_datasets = {
# -- DiffuserCam MirFlickr (7.58 GB) https://huggingface.co/datasets/bezzam/DiffuserCam-Lensless-Mirflickr-Dataset-NORM
"diffusercam_mirflickr": {
"size (GB)": 7.58,
"huggingface_repo": "bezzam/DiffuserCam-Lensless-Mirflickr-Dataset-NORM",
"psf": "psf.tiff",
"single_channel_psf": True,
"flipud": True,
"flip_lensed": True,
"downsample": 2,
"downsample_lensed": 2,
},
# -- TapeCam MirFlickr (10.5 GB) https://huggingface.co/datasets/bezzam/TapeCam-Mirflickr-25K
"tapecam_mirflickr": {
"size (GB)": 10.5,
"huggingface_repo": "bezzam/TapeCam-Mirflickr-25K",
"psf": "psf.png",
"display_res": [900, 1200],
"alignment": {"top_left": [45, 95], "height": 250},
},
# -- DigiCam CelebA (33.9 GB) https://huggingface.co/datasets/bezzam/DigiCam-CelebA-26K
"digicam_celeba": {
"size (GB)": 33.9,
"huggingface_repo": "bezzam/DigiCam-CelebA-26K",
"psf": "psf_simulated.png",
"rotate": True,
"split_seed": 0,
"downsample": 2,
"alignment": {"crop": {"vertical": [0, 525], "horizontal": [265, 695]}},
"simulation": {
"scene2mask": 0.25,
"mask2sensor": 0.002,
"object_height": 0.33,
"sensor": "rpi_hq",
"snr_db": None,
"downsample": None,
"random_vflip": False,
"random_hflip": False,
"quantize": False,
"vertical_shift": -117,
"horizontal_shift": -25,
},
},
# -- DigiCam MirFlickr (11.9 GB) https://huggingface.co/datasets/bezzam/DigiCam-Mirflickr-SingleMask-25K
"digicam_mirflickr": {
"size (GB)": 11.9,
"huggingface_repo": "bezzam/DigiCam-Mirflickr-SingleMask-25K",
"display_res": [900, 1200],
"rotate": True,
"alignment": {"top_left": [80, 100], "height": 200},
},
# DigiCam MirFlickr Mini (472 MB) https://huggingface.co/datasets/bezzam/DigiCam-Mirflickr-SingleMask-1K
"digicam_mirflickr_mini": {
"size (GB)": 0.472,
"huggingface_repo": "bezzam/DigiCam-Mirflickr-SingleMask-1K",
"display_res": [900, 1200],
"rotate": True,
"alignment": {"top_left": [80, 100], "height": 200},
},
# -- DigiCam MirFlickr Multimask (12 GB) https://huggingface.co/datasets/bezzam/DigiCam-Mirflickr-MultiMask-25K
"digicam_mirflickr_multi": {
"size (GB)": 12,
"huggingface_repo": "bezzam/DigiCam-Mirflickr-MultiMask-25K",
"display_res": [900, 1200],
"rotate": True,
"alignment": {"top_left": [80, 100], "height": 200},
},
# -- DigiCam MirFlickr Multimask Mini (477 MB) https://huggingface.co/datasets/bezzam/DigiCam-Mirflickr-MultiMask-1K
"digicam_mirflickr_multi_mini": {
"size (GB)": 0.477,
"huggingface_repo": "bezzam/DigiCam-Mirflickr-MultiMask-25K",
"display_res": [900, 1200],
"rotate": True,
"alignment": {"top_left": [80, 100], "height": 200},
},
# MultiLens MirFlickr Ambient (16.7 GB) https://huggingface.co/datasets/Lensless/MultiLens-Mirflickr-Ambient
"multilens_mirflickr_ambient": {
"size (GB)": 16.7,
"huggingface_repo": "Lensless/MultiLens-Mirflickr-Ambient",
"psf": "psf.png",
"display_res": [600, 600],
"alignment": {"top_left": [118, 220], "height": 123},
},
# MultiLens MirFlickr Ambient Mini (67.7 MB) https://huggingface.co/datasets/Lensless/MultiLens-Mirflickr-Ambient-100
"multilens_mirflickr_ambient_mini": {
"size (GB)": 0.0677,
"huggingface_repo": "Lensless/MultiLens-Mirflickr-Ambient-100",
"psf": "psf.png",
"display_res": [600, 600],
"alignment": {"top_left": [118, 220], "height": 123},
},
# Multilens MirFlickr Mini (427 MB) https://huggingface.co/datasets/Lensless/mirflickr_voronoi_1k
"multilens_mirflickr_mini": {
"size (GB)": 0.427,
"huggingface_repo": "Lensless/mirflickr_voronoi_1k",
"psf": "psf_measured.png",
"display_res": [900, 1200],
},
# Coded Aperture (MLS) MirFlickr 1K (467 MB) https://huggingface.co/datasets/Lensless/mirflickr_CA_fine_1k
"mls_mirflickr_1k": {
"size (GB)": 0.467,
"huggingface_repo": "Lensless/mirflickr_CA_fine_1k",
"psf": "psf_measured.png",
"display_res": [900, 1200],
# "alignment": {"top_left": [118, 220], "height": 123},
},
# Fresnel Zone Aperture MirFlickr 1K (454 MB) https://huggingface.co/datasets/Lensless/Mirflickr_FZA_fine_1k
"fza_mirflickr_1k": {
"size (GB)": 0.454,
"huggingface_repo": "Lensless/Mirflickr_FZA_fine_1k",
"psf": "psf_measured.png",
"display_res": [900, 1200],
# "alignment": {"top_left": [118, 220], "height": 123},
},
}
def print_available_datasets():
print("Available datasets:")
for dataset in available_datasets:
print(
f" - {dataset} ({available_datasets[dataset]['size (GB)']} GB) : https://huggingface.co/datasets/{available_datasets[dataset]['huggingface_repo']}"
)
def get_dataset(dataset_name, split, **kwargs):
"""
Get a dataset by name.
Parameters
----------
dataset_name : str
Name of the dataset from the available datasets in ``available_datasets``.
split : str
Split of the dataset to load (e.g. "train", "test").
Returns
-------
:py:class:`~torch.utils.data.Dataset`
Dataset object.
"""
if dataset_name not in available_datasets:
print_str_available_dataset = "Available datasets are:"
for dataset in available_datasets:
print_str_available_dataset += f"\n - {dataset} ({available_datasets[dataset]['size (GB)']} GB) : https://huggingface.co/datasets/{available_datasets[dataset]['huggingface_repo']}"
raise ValueError(
f"Dataset '{dataset_name}' not available.\n\n{print_str_available_dataset}"
)
assert split in ["train", "test"], "Split should be 'train' or 'test'"
dataset_config = available_datasets[dataset_name]
# replace dataset_config with anything from kwargs
dataset_config.update(kwargs)
return HFDataset(split=split, **dataset_config)
class DualDataset(Dataset):
"""
Abstract class for defining a dataset of paired lensed and lensless images.
"""
def __init__(
self,
indices=None,
# psf_path=None,
background=None,
# background_pix=(0, 15),
downsample=1,
flip=False,
flip_ud=False,
flip_lr=False,
transform_lensless=None,
transform_lensed=None,
input_snr=None,
**kwargs,
):
"""
Dataset consisting of lensless and corresponding lensed image.
Parameters
----------
indices : range or int or None
Indices of the images to use in the dataset (if integer, it should be interpreted as range(indices)), by default None.
psf_path : str
Path to the PSF of the imaging system, by default None.
background : :py:class:`~torch.Tensor` or None, optional
If not ``None``, background is removed from lensless images, by default ``None``. If PSF is provided, background is estimated from the PSF.
background_pix : tuple, optional
Pixels to use for background estimation, by default (0, 15).
downsample : int, optional
Downsample factor of the lensless images, by default 1.
flip : bool, optional
If ``True``, lensless images are flipped, by default ``False``.
transform_lensless : PyTorch Transform or None, optional
Transform to apply to the lensless images, by default ``None``. Note that this transform is applied on HWC images (different from torchvision).
transform_lensed : PyTorch Transform or None, optional
Transform to apply to the lensed images, by default ``None``. Note that this transform is applied on HWC images (different from torchvision).
input_snr : float, optional
If not ``None``, Poisson noise is added to the lensless images to match the given SNR.
"""
if isinstance(indices, int):
indices = range(indices)
self.indices = indices
self.background = background
self.input_snr = input_snr
self.downsample = downsample
self.flip = flip
self.flip_ud = flip_ud
self.flip_lr = flip_lr
self.transform_lensless = transform_lensless
self.transform_lensed = transform_lensed
# self.psf = None
# if psf_path is not None:
# psf, background = load_psf(
# psf_path,
# downsample=downsample,
# return_float=True,
# return_bg=True,
# bg_pix=background_pix,
# )
# if self.background is None:
# self.background = background
# self.psf = torch.from_numpy(psf)
# if self.transform_lensless is not None:
# self.psf = self.transform_lensless(self.psf)
@abstractmethod
def __len__(self):
"""
Abstract method to get the length of the dataset. It should take into account the indices parameter.
"""
raise NotImplementedError
@abstractmethod
def _get_images_pair(self, idx):
"""
Abstract method to get the lensed and lensless images. Should return a pair (lensless, lensed) of numpy arrays with values in [0,1].
Parameters
----------
idx : int
images index
"""
raise NotImplementedError
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.item()
if self.indices is not None:
idx = self.indices[idx]
lensless, lensed = self._get_images_pair(idx)
if isinstance(lensless, np.ndarray):
# expected case
if self.downsample != 1.0:
lensless = resize(lensless, factor=1 / self.downsample)
lensed = resize(lensed, factor=1 / self.downsample)
lensless = torch.from_numpy(lensless)
lensed = torch.from_numpy(lensed)
else:
# torch tensor
# This mean get_images_pair returned a torch tensor. This isn't recommended, if possible get_images_pair should return a numpy array
# In this case it should also have applied the downsampling
pass
# If [H, W, C] -> [D, H, W, C]
if len(lensless.shape) == 3:
lensless = lensless.unsqueeze(0)
if len(lensed.shape) == 3:
lensed = lensed.unsqueeze(0)
if self.background is not None:
lensless = lensless - self.background
lensless = torch.clamp(lensless, min=0)
# add noise
if self.input_snr is not None:
lensless = add_shot_noise(lensless, self.input_snr)
# flip image x and y if needed
if self.flip:
lensless = torch.rot90(lensless, dims=(-3, -2), k=2)
lensed = torch.rot90(lensed, dims=(-3, -2), k=2)
if self.flip_ud:
lensless = torch.flip(lensless, dims=(-4, -3))
lensed = torch.flip(lensed, dims=(-4, -3))
if self.flip_lr:
lensless = torch.flip(lensless, dims=(-4, -2))
lensed = torch.flip(lensed, dims=(-4, -2))
if self.transform_lensless:
lensless = self.transform_lensless(lensless)
if self.transform_lensed:
lensed = self.transform_lensed(lensed)
return lensless, lensed
class SimulatedFarFieldDataset(DualDataset):
"""
Dataset of propagated images (through simulation) from a Torch Dataset. :py:class:`lensless.utils.simulation.FarFieldSimulator` is used for simulation,
assuming a far-field propagation and a shift-invariant system with a single point spread function (PSF).
"""
def __init__(
self,
dataset,
simulator,
pre_transform=None,
dataset_is_CHW=False,
flip=False,
vertical_shift=None,
horizontal_shift=None,
crop=None,
downsample=1,
**kwargs,
):
"""
Parameters
----------
dataset : :py:class:`torch.utils.data.Dataset`
Dataset to propagate. Should output images with shape [H, W, C] unless ``dataset_is_CHW`` is ``True`` (and therefore images have the dimension ordering of [C, H, W]).
simulator : :py:class:`lensless.utils.simulation.FarFieldSimulator`
Simulator object used on images from ``dataset``. Waveprop simulator to use for the simulation. It is expected to have ``is_torch = True``.
pre_transform : PyTorch Transform or None, optional
Transform to apply to the images before simulation, by default ``None``. Note that this transform is applied on HCW images (different from torchvision).
dataset_is_CHW : bool, optional
If True, the input dataset is expected to output images with shape [C, H, W], by default ``False``.
flip : bool, optional
If True, images are flipped beffore the simulation, by default ``False``.
"""
# we do the flipping before the simualtion
super(SimulatedFarFieldDataset, self).__init__(flip=False, **kwargs)
assert isinstance(dataset, Dataset)
self.dataset = dataset
self.n_files = len(dataset)
self.dataset_is_CHW = dataset_is_CHW
self._pre_transform = pre_transform
self.flip_pre_sim = flip
self.vertical_shift = vertical_shift
self.horizontal_shift = horizontal_shift
self.crop = crop.copy() if crop is not None else None
if downsample != 1:
if self.vertical_shift is not None:
self.vertical_shift = int(self.vertical_shift // downsample)
if self.horizontal_shift is not None:
self.horizontal_shift = int(self.horizontal_shift // downsample)
if crop is not None:
self.crop["vertical"][0] = int(self.crop["vertical"][0] // downsample)
self.crop["vertical"][1] = int(self.crop["vertical"][1] // downsample)
self.crop["horizontal"][0] = int(self.crop["horizontal"][0] // downsample)
self.crop["horizontal"][1] = int(self.crop["horizontal"][1] // downsample)
# check simulator
assert isinstance(simulator, FarFieldSimulator), "Simulator should be a FarFieldSimulator"
assert simulator.is_torch, "Simulator should be a pytorch simulator"
assert simulator.fft_shape is not None, "Simulator should have a psf"
self.sim = simulator
@property
def psf(self):
return self.sim.get_psf()
def get_image(self, index):
return self.dataset[index]
def _get_images_pair(self, index):
# load image
img, _ = self.get_image(index)
# convert to HWC for simulator and transform
if self.dataset_is_CHW:
img = img.moveaxis(-3, -1)
if self.flip_pre_sim:
img = torch.rot90(img, dims=(-3, -2))
if self._pre_transform is not None:
img = self._pre_transform(img)
lensless, lensed = self.sim.propagate_image(img, return_object_plane=True)
if self.vertical_shift is not None:
lensed = torch.roll(lensed, self.vertical_shift, dims=-3)
if self.horizontal_shift is not None:
lensed = torch.roll(lensed, self.horizontal_shift, dims=-2)
if lensed.shape[-1] == 1 and lensless.shape[-1] == 3:
# copy to 3 channels
lensed = lensed.repeat(1, 1, 3)
assert (
lensed.shape[-1] == lensless.shape[-1]
), "Lensed and lensless should have same number of channels"
return lensless, lensed
def __len__(self):
if self.indices is None:
return self.n_files
else:
return len([x for x in self.indices if x < self.n_files])
class MeasuredDatasetSimulatedOriginal(DualDataset):
"""
Abstract class for defining a dataset of paired lensed and lensless images.
Dataset consisting of lensless image captured from a screen and the corresponding image shown on the screen.
Unlike :py:class:`lensless.utils.dataset.MeasuredDataset`, the ground-truth lensed image is simulated using a :py:class:`lensless.utils.simulation.FarFieldSimulator`
object rather than measured with a lensed camera.
The class assumes that the ``measured_dir`` and ``original_dir`` have file names that match.
The method ``_get_images_pair`` must be defined.
"""
def __init__(
self,
measured_dir,
original_dir,
simulator,
measurement_ext="png",
original_ext="jpg",
downsample=1,
background=None,
flip=False,
**kwargs,
):
"""
Dataset consisting of lensless image captured from a screen and the corresponding image shown on screen.
Parameters
----------
"""
super(MeasuredDatasetSimulatedOriginal, self).__init__(
downsample=1, background=background, flip=flip, **kwargs
)
self.pre_downsample = downsample
self.measured_dir = measured_dir
self.original_dir = original_dir
assert os.path.isdir(self.measured_dir)
assert os.path.isdir(self.original_dir)
self.measurement_ext = measurement_ext.lower()
self.original_ext = original_ext.lower()
files = natural_sort(glob.glob(os.path.join(self.measured_dir, "*." + measurement_ext)))
self.files = [os.path.basename(fn) for fn in files]
if len(self.files) == 0:
raise FileNotFoundError(
f"No files found in {self.measured_dir} with extension {self.measurement_ext}"
)
# check that corresponding files exist
for fn in self.files:
original_fp = os.path.join(self.original_dir, fn[:-3] + self.original_ext)
assert os.path.exists(original_fp), f"File {original_fp} does not exist"
# check simulator
assert isinstance(simulator, FarFieldSimulator), "Simulator should be a FarFieldSimulator"
assert simulator.is_torch, "Simulator should be a pytorch simulator"
assert simulator.fft_shape is None, "Simulator should not have a psf"
self.sim = simulator
def __len__(self):
if self.indices is None:
return len(self.files)
else:
return len([i for i in self.indices if i < len(self.files)])
# def _get_images_pair(self, idx):
# if self.image_ext == "npy" or self.image_ext == "npz":
# lensless_fp = os.path.join(self.lensless_dir, self.files[idx])
# original_fp = os.path.join(self.original_dir, self.files[idx])
# lensless = np.load(lensless_fp)
# lensless = resize(lensless, factor=1 / self.downsample)
# original = np.load(original_fp[:-3] + self.original_ext)
# else:
# # more standard image formats: png, jpg, tiff, etc.
# lensless_fp = os.path.join(self.lensless_dir, self.files[idx])
# original_fp = os.path.join(self.original_dir, self.files[idx])
# lensless = load_image(lensless_fp, downsample=self.pre_downsample)
# original = load_image(
# original_fp[:-3] + self.original_ext, downsample=self.pre_downsample
# )
# # convert to float
# if lensless.dtype == np.uint8:
# lensless = lensless.astype(np.float32) / 255
# original = original.astype(np.float32) / 255
# else:
# # 16 bit
# lensless = lensless.astype(np.float32) / 65535
# original = original.astype(np.float32) / 65535
# # convert to torch
# lensless = torch.from_numpy(lensless)
# original = torch.from_numpy(original)
# # project original image to lensed space
# with torch.no_grad():
# lensed = self.sim.propagate_image()
# return lensless, lensed
class DigiCamCelebA(MeasuredDatasetSimulatedOriginal):
def __init__(
self,
celeba_root,
data_dir=None,
psf_path=None,
downsample=1,
flip=True,
vertical_shift=None,
horizontal_shift=None,
crop=None,
simulation_config=None,
**kwargs,
):
"""
Some parameters default to work for the ``celeba_adafruit_random_2mm_20230720_10K`` dataset,
namely: flip, vertical_shift, horizontal_shift, crop, simulation_config.
Parameters
----------
celeba_root : str
Path to the CelebA dataset.
data_dir : str, optional
Path to the lensless images, by default looks inside the ``data`` folder. Can download if not available.
psf_path : str, optional
Path to the PSF of the imaging system, by default looks inside the ``data/psf`` folder. Can download if not available.
downsample : int, optional
Downsample factor of the lensless images, by default 1.
flip : bool, optional
If True, measurements are flipped, by default ``True``. Does not get applied to the original images.
vertical_shift : int, optional
Vertical shift (in pixels) of the lensed images to align.
horizontal_shift : int, optional
Horizontal shift (in pixels) of the lensed images to align.
crop : dict, optional
Dictionary of crop parameters (vertical: [start, end], horizontal: [start, end]) to select region of interest.
"""
if vertical_shift is None:
# default to (no downsampling) of celeba_adafruit_random_2mm_20230720_10K
vertical_shift = -85
horizontal_shift = -5
if crop is None:
crop = {"vertical": [30, 560], "horizontal": [285, 720]}
self.crop = crop
self.vertical_shift = vertical_shift
self.horizontal_shift = horizontal_shift
if downsample != 1:
self.vertical_shift = int(self.vertical_shift // downsample)
self.horizontal_shift = int(self.horizontal_shift // downsample)
self.crop["vertical"][0] = int(self.crop["vertical"][0] // downsample)
self.crop["vertical"][1] = int(self.crop["vertical"][1] // downsample)
self.crop["horizontal"][0] = int(self.crop["horizontal"][0] // downsample)
self.crop["horizontal"][1] = int(self.crop["horizontal"][1] // downsample)
# download dataset if necessary
if data_dir is None:
data_dir = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"data",
"celeba_adafruit_random_2mm_20230720_10K",
)
if not os.path.isdir(data_dir):
main_dir = os.path.join(os.path.dirname(__file__), "..", "..", "data")
print("DigiCam CelebA dataset not found.")
try:
from torchvision.datasets.utils import download_and_extract_archive
except ImportError:
exit()
msg = "Do you want to download this dataset of 10K examples (12.2GB)?"
# default to yes if no input is given
valid = input("%s (Y/n) " % msg).lower() != "n"
if valid:
url = "https://drive.switch.ch/index.php/s/9NNGCJs3DoBDGlY/download"
filename = "celeba_adafruit_random_2mm_20230720_10K.zip"
download_and_extract_archive(url, main_dir, filename=filename, remove_finished=True)
# download PSF if necessary
if psf_path is None:
psf_path = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"data",
"psf",
"adafruit_random_2mm_20231907.png",
)
if not os.path.exists(psf_path):
try:
from torchvision.datasets.utils import download_url
except ImportError:
exit()
msg = "Do you want to download the PSF (38.8MB)?"
# default to yes if no input is given
valid = input("%s (Y/n) " % msg).lower() != "n"
output_path = os.path.join(os.path.dirname(__file__), "..", "..", "data", "psf")
if valid:
url = "https://drive.switch.ch/index.php/s/kfN5vOqvVkNyHmc/download"
filename = "adafruit_random_2mm_20231907.png"
download_url(url, output_path, filename=filename)
# load PSF
self.flip_measurement = flip
psf, background = load_psf(
psf_path,
downsample=downsample * 4, # PSF is 4x the resolution of the images
return_float=True,
return_bg=True,
flip=flip,
bg_pix=(0, 15),
)
self.psf = torch.from_numpy(psf)
# create simulator
simulation_config["output_dim"] = tuple(self.psf.shape[-3:-1])
simulator = FarFieldSimulator(
is_torch=True,
**simulation_config,
)
super().__init__(
measured_dir=data_dir,
original_dir=os.path.join(celeba_root, "celeba", "img_align_celeba"),
simulator=simulator,
measurement_ext="png",
original_ext="jpg",
downsample=downsample,
background=background,
flip=False, # will do flipping only on measurement
**kwargs,
)
def _get_images_pair(self, idx):
# more standard image formats: png, jpg, tiff, etc.
lensless_fp = os.path.join(self.measured_dir, self.files[idx])
original_fp = os.path.join(self.original_dir, self.files[idx][:-3] + self.original_ext)
lensless = load_image(
lensless_fp, downsample=self.pre_downsample, flip=self.flip_measurement
)
original = load_image(original_fp[:-3] + self.original_ext)
# convert to float
if lensless.dtype == np.uint8:
lensless = lensless.astype(np.float32) / 255
original = original.astype(np.float32) / 255
else:
# 16 bit
lensless = lensless.astype(np.float32) / 65535
original = original.astype(np.float32) / 65535
# convert to torch
lensless = torch.from_numpy(lensless)
original = torch.from_numpy(original)
# project original image to lensed space
with torch.no_grad():
lensed = self.sim.propagate_image(original, return_object_plane=True)
if self.vertical_shift is not None:
lensed = torch.roll(lensed, self.vertical_shift, dims=-3)
if self.horizontal_shift is not None:
lensed = torch.roll(lensed, self.horizontal_shift, dims=-2)
return lensless, lensed
class MeasuredDataset(DualDataset):
"""
Dataset consisting of lensless and corresponding lensed image.
It can be used with a PyTorch DataLoader to load a batch of lensless and corresponding lensed images.
Unless the setup is perfectly calibrated, one should expect to have to use ``transform_lensed`` to adjust the alignment and rotation.
"""
def __init__(
self,
root_dir,
lensless_fn="diffuser",
lensed_fn="lensed",
image_ext="npy",
**kwargs,
):
"""
Dataset consisting of lensless and corresponding lensed image. Default parameters are for the
`DiffuserCam Lensless Mirflickr Dataset (DLMD) <https://waller-lab.github.io/LenslessLearning/dataset.html>`_.
Parameters
----------
root_dir : str
Path to the test dataset. It is expected to contain two folders: ones of lensless images and one of lensed images.
lensless_fn : str, optional
Name of the folder containing the lensless images, by default "diffuser".
lensed_fn : str, optional
Name of the folder containing the lensed images, by default "lensed".
image_ext : str, optional
Extension of the images, by default "npy".
"""
super(MeasuredDataset, self).__init__(**kwargs)
self.root_dir = root_dir
self.lensless_dir = os.path.join(root_dir, lensless_fn)
self.lensed_dir = os.path.join(root_dir, lensed_fn)
assert os.path.isdir(self.lensless_dir)
assert os.path.isdir(self.lensed_dir)
self.image_ext = image_ext.lower()
files = natural_sort(glob.glob(os.path.join(self.lensless_dir, "*." + image_ext)))
self.files = [os.path.basename(fn) for fn in files]
if len(self.files) == 0:
raise FileNotFoundError(
f"No files found in {self.lensless_dir} with extension {image_ext}"
)
def __len__(self):
if self.indices is None:
return len(self.files)
else:
return len([i for i in self.indices if i < len(self.files)])
def _get_images_pair(self, idx):
if self.image_ext == "npy" or self.image_ext == "npz":
lensless_fp = os.path.join(self.lensless_dir, self.files[idx])
lensed_fp = os.path.join(self.lensed_dir, self.files[idx])
lensless = np.load(lensless_fp)
lensed = np.load(lensed_fp)
else:
# more standard image formats: png, jpg, tiff, etc.
lensless_fp = os.path.join(self.lensless_dir, self.files[idx])
lensed_fp = os.path.join(self.lensed_dir, self.files[idx])
lensless = load_image(lensless_fp)
lensed = load_image(lensed_fp)
# convert to float
if lensless.dtype == np.uint8:
lensless = lensless.astype(np.float32) / 255
lensed = lensed.astype(np.float32) / 255
else:
# 16 bit
lensless = lensless.astype(np.float32) / 65535
lensed = lensed.astype(np.float32) / 65535
return lensless, lensed
class DiffuserCamMirflickr(MeasuredDataset):
"""
Helper class for DiffuserCam Mirflickr dataset.
Note that image colors are in BGR format: https://github.com/Waller-Lab/LenslessLearning/blob/master/utils.py#L432
"""
def __init__(
self,
dataset_dir,
psf_path,
downsample=2,
**kwargs,
):
# check psf path exist
if not os.path.exists(psf_path):
psf_path = os.path.join(
os.path.dirname(__file__), "..", "..", "data", "psf", "diffusercam_psf.tiff"
)
try:
from torchvision.datasets.utils import download_url
except ImportError:
exit()
msg = "Do you want to download the DiffuserCam PSF (5.9MB)?"
# default to yes if no input is given
valid = input("%s (Y/n) " % msg).lower() != "n"
output_path = os.path.join(os.path.dirname(__file__), "..", "..", "data", "psf")
if valid:
url = "https://drive.switch.ch/index.php/s/BteiuEcONmhmDSn/download"
filename = "diffusercam_psf.tiff"
download_url(url, output_path, filename=filename)
psf, background = load_psf(
psf_path,
downsample=downsample * 4, # PSF is 4x the resolution of the images
return_float=True,
return_bg=True,
bg_pix=(0, 15),
)
transform_BRG2RGB = transforms.Lambda(lambda x: x[..., [2, 1, 0]])
self.psf = transform_BRG2RGB(torch.from_numpy(psf))
self.allowed_idx = np.arange(2, 25001)
assert os.path.isdir(os.path.join(dataset_dir, "diffuser_images")) and os.path.isdir(
os.path.join(dataset_dir, "ground_truth_lensed")
), "Dataset should contain 'diffuser_images' and 'ground_truth_lensed' folders. It can be downloaded from https://waller-lab.github.io/LenslessLearning/dataset.html"
super().__init__(
root_dir=dataset_dir,
background=background,
downsample=downsample,
flip=False,
transform_lensless=transform_BRG2RGB,
transform_lensed=transform_BRG2RGB,
lensless_fn="diffuser_images",
lensed_fn="ground_truth_lensed",
image_ext="npy",
**kwargs,
)
def _get_images_pair(self, idx):
assert idx >= self.allowed_idx.min(), f"idx should be >= {self.allowed_idx.min()}"
assert idx <= self.allowed_idx.max(), f"idx should be <= {self.allowed_idx.max()}"
fn = f"im{idx}.npy"
lensless_fp = os.path.join(self.lensless_dir, fn)
lensed_fp = os.path.join(self.lensed_dir, fn)
lensless = np.load(lensless_fp)
lensed = np.load(lensed_fp)
return lensless, lensed
class DiffuserCamTestDataset(MeasuredDataset):
"""
Dataset consisting of lensless and corresponding lensed image. This is the standard dataset used for benchmarking.
"""
def __init__(
self,
data_dir=None,
n_files=None,
downsample=2,
):
"""
Dataset consisting of lensless and corresponding lensed image. Default parameters are for the test set of
`DiffuserCam Lensless Mirflickr Dataset (DLMD) <https://waller-lab.github.io/LenslessLearning/dataset.html>`_.
Parameters
----------
data_dir : str, optional
The path to ``DiffuserCam_Test`` dataset, by default looks inside the ``data`` folder.
n_files : int, optional
Number of image pairs to load in the dataset , by default use all.
downsample : int, optional
Downsample factor of the lensless images, by default 2. Note that the PSF has a resolution of 4x of the images.
"""
# download dataset if necessary
if data_dir is None:
data_dir = os.path.join(
os.path.dirname(__file__), "..", "..", "data", "DiffuserCam_Test"
)
if not os.path.isdir(data_dir):
main_dir = os.path.join(os.path.dirname(__file__), "..", "..", "data")
print("DiffuserCam test set not found for benchmarking.")
try:
from torchvision.datasets.utils import download_and_extract_archive
except ImportError:
exit()
msg = "Do you want to download the dataset (3.5GB)?"
# default to yes if no input is given
valid = input("%s (Y/n) " % msg).lower() != "n"
if valid:
url = "https://drive.switch.ch/index.php/s/D3eRJ6PRljfHoH8/download"
filename = "DiffuserCam_Test.zip"
download_and_extract_archive(url, main_dir, filename=filename, remove_finished=True)
psf_fp = os.path.join(data_dir, "psf.tiff")
psf, background = load_psf(
psf_fp,
downsample=downsample * 4, # PSF is 4x the resolution of the images
return_float=True,
return_bg=True,
bg_pix=(0, 15),
flip_ud=True,
flip_lr=False,
)
# transform from BGR to RGB
transform_BRG2RGB = transforms.Lambda(lambda x: x[..., [2, 1, 0]])
self.psf = transform_BRG2RGB(torch.from_numpy(psf))
if n_files is None:
indices = None
else:
indices = range(n_files)
super().__init__(
root_dir=data_dir,
indices=indices,
background=background,
downsample=downsample,
flip=False,
flip_ud=True,
flip_lr=False,
transform_lensless=transform_BRG2RGB,
transform_lensed=transform_BRG2RGB,
lensless_fn="diffuser",
lensed_fn="lensed",
image_ext="npy",
)
class SimulatedDatasetTrainableMask(SimulatedFarFieldDataset):
"""
Dataset of propagated images (through simulation) from a Torch Dataset with learnable mask.
The `waveprop <https://github.com/ebezzam/waveprop/blob/master/waveprop/simulation.py>`_ package is used for the simulation,
assuming a far-field propagation and a shift-invariant system with a single point spread function (PSF).
To ensure autograd compatibility, the dataloader should have ``num_workers=0``.
"""
def __init__(
self,
mask,
dataset,
simulator,
**kwargs,
):
"""
Parameters
----------
mask : :py:class:`lensless.hardware.trainable_mask.TrainableMask`
Mask to use for simulation. Should be a 4D tensor with shape [1, H, W, C]. Simulation of multi-depth data is not supported yet.