dactylroot commited on
Commit
bd00799
1 Parent(s): 5fe3c1e

updated init.py

Browse files
Files changed (1) hide show
  1. __init__.py +96 -40
__init__.py CHANGED
@@ -1,43 +1,96 @@
1
- import torch
2
- import torchvision
3
- from torchvision import transforms
4
- from torch import Tensor
5
 
6
- import pandas as pd
7
- from skimage import io
8
- import matplotlib.pyplot as plt
9
- from pathlib import Path
 
10
 
11
  # Ignore warnings
12
- import warnings
13
- warnings.filterwarnings("ignore")
14
 
15
- plt.ion() # interactive mode
16
-
17
- class MORRIS(torch.utils.data.Dataset):
18
  _storage_csv='morris.csv'
19
  _storage_jpg='jpgs'
20
- def __init__(self,root=Path(__file__).parent,transform=False):
21
- self.storage = Path(root)
22
  self.transform = transform
23
- self.index = pd.read_csv(self.storage / self._storage_csv)
24
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def __len__(self):
26
  return len(self.index)
27
-
28
  def __getitem__(self,idx):
29
  item = self.index.iloc[idx].to_dict()
30
- image = io.imread(self.storage / self._storage_jpg / self.index.iloc[idx].filename)
31
-
32
  if self.transform:
33
  image = self.transform(image)
34
-
35
  item['image'] = image
36
  return item
37
-
38
- def showitem(self,idx):
39
- plt.imshow(transforms.ToPILImage()(self.__getitem__(idx)['image']))
40
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def _self_validate(self):
42
  """try loading each image in the dataset"""
43
  allgood=True
@@ -48,50 +101,53 @@ class MORRIS(torch.utils.data.Dataset):
48
  allgood=False
49
  print(f"couldn't load {self.index.iloc[idx].filename}")
50
  if allgood:
51
- print(f"All Good! Loaded {len(self)} images.")
52
 
53
  class Deframe(object):
54
  """check for uniform color boundaries on edges of input and crop them away"""
55
-
 
56
  def __init__(self,aggressive=False,maxPixelFrame=20):
57
  self.alpha = 0.1 if aggressive else 0.01
58
  self.maxPixelFrame = maxPixelFrame
59
-
60
  def _map2idx(self,frameMap):
61
  try:
62
  return frameMap.tolist().index(False)
63
  except ValueError:
64
  return self.maxPixelFrame
65
-
66
  def _Border(self,img: Tensor):
67
  """ take greyscale Tensor
68
  return left,right,top,bottom border size identified """
 
69
  top = left = right = bottom = 0
70
-
71
  # expected image variance
72
  hvar,wvar = torch.mean(torch.var(img,dim=0)), torch.mean(torch.var(img,dim=1))
73
-
74
  # use image variance and alpha to identify too-uniform frame borders
75
  top = torch.var(img[:self.maxPixelFrame,:],dim=1) < wvar*(1+self.alpha)
76
  top = self._map2idx(top)
77
-
78
  bottom = torch.var(img[-self.maxPixelFrame:,:],dim=1) < wvar*(1+self.alpha)
79
  bottom = self._map2idx(bottom)
80
-
81
  left = torch.var(img[:,:self.maxPixelFrame],dim=0) < hvar*(1+self.alpha)
82
  left = self._map2idx(left)
83
-
84
  right = torch.var(img[:,-self.maxPixelFrame:],dim=0) < hvar*(1+self.alpha)
85
  right = self._map2idx(right)
86
-
87
  return (top,bottom,right,left)
88
-
89
  def __call__(self,img: Tensor):
 
90
  top,bottom,right,left = self._Border(torchvision.transforms.Grayscale()(img)[0])
91
-
92
  height = img.shape[1]-(top+bottom)
93
  width = img.shape[2]-(left+right)
94
-
95
  print(f"t{top} b{bottom} l{left} r{right}")
96
-
97
- return torchvision.transforms.functional.crop(img,top,left,height,width)
 
 
 
 
 
1
 
2
+ import pandas as _pd
3
+ from skimage import io as _io
4
+ import matplotlib.pyplot as _plt
5
+ from pathlib import Path as _Path
6
+ from PIL import Image as _Image
7
 
8
  # Ignore warnings
9
+ import warnings as _warnings
10
+ _warnings.filterwarnings("ignore")
11
 
12
+ _plt.ion() # interactive mode
13
+
14
+ class MORRIS():
15
  _storage_csv='morris.csv'
16
  _storage_jpg='jpgs'
17
+ def __init__(self,root=_Path(__file__).parent,transform=False):
18
+ self.storage = _Path(root)
19
  self.transform = transform
20
+ self.index = _pd.read_csv(self.storage / self._storage_csv)
21
+
22
+ def torch(self):
23
+ import torch
24
+ from torchvision import transforms
25
+
26
+ class MORRISTORCH(torch.utils.data.Dataset,MORRIS):
27
+
28
+ def __init__(self,root=_Path(__file__).parent,transform=False):
29
+ super().__init__(root,transform)
30
+
31
+ def show(self,idx):
32
+ name=None
33
+ if isinstance(idx,str):
34
+ if idx in self.index.name.values:
35
+ idx = self.index.index[self.index.name==idx][0]
36
+ idx = int(idx)
37
+ name = self.index.name[idx]
38
+ print(f"found item {idx} by name {name}")
39
+ else:
40
+ raise ValueError('item name not found')
41
+ if isinstance(idx,int):
42
+ name = self.index.name[idx]
43
+ _plt.title(name)
44
+ _plt.imshow(transforms.ToPILImage()(self.__getitem__(idx)[0]))
45
+ else:
46
+ _plt.imshow(transforms.ToPILImage()(idx))
47
+
48
+ def __getitem__(self,idx):
49
+ item = self.index.iloc[idx].to_dict()
50
+ image = _io.imread(self.storage / self._storage_jpg / self.index.iloc[idx].filename)
51
+ image = torch.tensor(image).permute(2,0,1)
52
+ if self.transform:
53
+ image = self.transform(image)
54
+
55
+ item = [image,item['name'],item['year']]
56
+ return item
57
+
58
+ return MORRISTORCH(str(self.storage),self.transform)
59
+
60
  def __len__(self):
61
  return len(self.index)
62
+
63
  def __getitem__(self,idx):
64
  item = self.index.iloc[idx].to_dict()
65
+ image = _io.imread(self.storage / self._storage_jpg / self.index.iloc[idx].filename)
66
+
67
  if self.transform:
68
  image = self.transform(image)
69
+
70
  item['image'] = image
71
  return item
72
+
73
+ def show(self,idx):
74
+ if isinstance(idx,str):
75
+ if idx in self.index.name.values:
76
+ idx = self.index.index[self.index.name==idx][0]
77
+ idx = int(idx)
78
+ name = self.index.name[idx]
79
+ print(f"found item {idx} by name {name}")
80
+ else:
81
+ raise ValueError('item name not found')
82
+ if isinstance(idx,int):
83
+ _item = self.__getitem__(idx)
84
+ image = _item['image']
85
+ name = _item['name']
86
+ _plt.title(name)
87
+ _plt.imshow(_Image.fromarray(image))
88
+ else:
89
+ try:
90
+ _plt.imshow(_Image.fromarray(idx))
91
+ except AttributeError:
92
+ _plt.imshow(_Image.fromarray(idx.permute(1,2,0).numpy()))
93
+
94
  def _self_validate(self):
95
  """try loading each image in the dataset"""
96
  allgood=True
 
101
  allgood=False
102
  print(f"couldn't load {self.index.iloc[idx].filename}")
103
  if allgood:
104
+ print(f"All good. {len(self)} images loadable.")
105
 
106
  class Deframe(object):
107
  """check for uniform color boundaries on edges of input and crop them away"""
108
+ from torch import Tensor
109
+
110
  def __init__(self,aggressive=False,maxPixelFrame=20):
111
  self.alpha = 0.1 if aggressive else 0.01
112
  self.maxPixelFrame = maxPixelFrame
113
+
114
  def _map2idx(self,frameMap):
115
  try:
116
  return frameMap.tolist().index(False)
117
  except ValueError:
118
  return self.maxPixelFrame
119
+
120
  def _Border(self,img: Tensor):
121
  """ take greyscale Tensor
122
  return left,right,top,bottom border size identified """
123
+ import torch
124
  top = left = right = bottom = 0
125
+
126
  # expected image variance
127
  hvar,wvar = torch.mean(torch.var(img,dim=0)), torch.mean(torch.var(img,dim=1))
128
+
129
  # use image variance and alpha to identify too-uniform frame borders
130
  top = torch.var(img[:self.maxPixelFrame,:],dim=1) < wvar*(1+self.alpha)
131
  top = self._map2idx(top)
132
+
133
  bottom = torch.var(img[-self.maxPixelFrame:,:],dim=1) < wvar*(1+self.alpha)
134
  bottom = self._map2idx(bottom)
135
+
136
  left = torch.var(img[:,:self.maxPixelFrame],dim=0) < hvar*(1+self.alpha)
137
  left = self._map2idx(left)
138
+
139
  right = torch.var(img[:,-self.maxPixelFrame:],dim=0) < hvar*(1+self.alpha)
140
  right = self._map2idx(right)
141
+
142
  return (top,bottom,right,left)
143
+
144
  def __call__(self,img: Tensor):
145
+ import torchvision
146
  top,bottom,right,left = self._Border(torchvision.transforms.Grayscale()(img)[0])
147
+
148
  height = img.shape[1]-(top+bottom)
149
  width = img.shape[2]-(left+right)
150
+
151
  print(f"t{top} b{bottom} l{left} r{right}")
152
+
153
+ return torchvision.transforms.functional.crop(img,top,left,height,width)