[171cba]: / 4x / reference / batch.py

Download this file

271 lines (187 with data), 7.1 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
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
# Files
import os
import pickle
import sys
# Basic
import numpy as np
# Image Processing
import skimage as ski
from skimage import io, feature, morphology, filter, exposure, color, transform, measure
import scipy.signal as sig
from scipy.spatial import distance
from scipy.ndimage import maximum_filter, minimum_filter, binary_fill_holes
# Stats
import scipy.stats as st
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
matplotlib.rcParams["figure.figsize"] = (16, 10)
# <codecell>
# Read files
files = []
directory = "../data/"
for i in os.listdir(directory) :
if i.endswith(".jpg") : # if it's a jpg
if not i.endswith("_processed.jpg") : # and isn't a processed image
files.append(directory + i) # then add it to the list to be processed
files = [files[50]]
io.imshow(io.imread(files[0]))
# <codecell>
# Iterate over files
for f in files :
# If it's not been processed before
if not os.path.exists(f + "_processed.jpg") :
### PROCESSING
# Read the image
A = io.imread(f)
# Constrast enhancement
B = exposure.adjust_sigmoid(A, gain=12)
# Extract luminosity
C = color.rgb2xyz(B)[:, :, 1]
# Apply adaptive thresholding
D = filter.threshold_adaptive(C, 301)
# Clean
E = morphology.remove_small_objects(~morphology.remove_small_objects(~D, 100), 100)
# Save to disk
io.imsave(f + "_processed.jpg", ski.img_as_float(E))
# Downsample for Gabor filtering
Es = ski.img_as_float(transform.rescale(E, 0.25))
else :
# Otherwise, we've processed it before, so read it in for speed
A = io.imread(f)
E = ski.img_as_float(io.imread(f + "_processed.jpg"))
Es = ski.img_as_float(transform.rescale(E, 0.25))
# <codecell>
A = io.imread(files[0])[:2000, 1000:-1000, :]
A2 = filter.gaussian_filter(A, 5)
B1 = exposure.adjust_sigmoid(A, gain=12)
B2 = exposure.adjust_sigmoid(A2, gain=12)
C1 = color.rgb2xyz(B1)[:, :, 1]
C2 = color.rgb2xyz(B2)[:, :, 1]
D1 = filter.threshold_adaptive(C1, 301)
D2 = filter.threshold_adaptive(C2, 301)
E1 = morphology.remove_small_objects(~morphology.remove_small_objects(~D1, 100), 100)
E2 = morphology.remove_small_objects(~morphology.remove_small_objects(~D2, 100), 100)
d1 = filter.threshold_adaptive(C1, 301, offset=-0.01)
d2 = filter.threshold_adaptive(C2, 301, offset=-0.01)
e1 = morphology.remove_small_objects(~morphology.remove_small_objects(~d1, 100), 100)
e2 = morphology.remove_small_objects(~morphology.remove_small_objects(~d2, 100), 100)
print np.abs(E1 - e1).sum()
print np.abs(E2 - e2).sum()
# <codecell>
(A2.shape[0] * A2.shape[1])
# <codecell>
pixelscales = np.arange(15, 55, 2)
gaborscales = 4. / pixelscales # 2 to 20 pixels
orientations = np.linspace(0, np.pi * 11./12., 12) # 0 to 180 degrees in 15 degree increments
# Results array
gabor = np.zeros((len(orientations), len(gaborscales)))
# Perform Gabor filtering
for i, iv in enumerate(orientations) :
for j, jv in enumerate(gaborscales) :
gaborReal, gaborImag = filter.gabor_filter(Es, jv, iv)
gabor[i, j] = np.sqrt(np.sum(np.abs(gaborReal) ** 2) + np.sum(np.abs(gaborImag) ** 2)) # Return energy
print "Thread %s. Gabor filtering. Completion : %f" % (sys.argv[1], (i / float(len(orientations))))
# Determine orientation-independent scale which fits best
optimalscale = np.argmax(np.sum(gabor, axis = 0))
# At this scale, calculate directionality coefficient
g = gabor[:, optimalscale]
directionality = (g.max() - g.min()) / g.max()
# <codecell>
scaleent = []
scaleentstd = []
roylac = []
# Characteristic scale
s = pixelscales[optimalscale]
# Generate a disk at this scale
circle = morphology.disk(s)
circlesize = circle.sum()
# Convolve with image
Y = sig.fftconvolve(E, circle, "valid")
# Compute information entropy
px = Y.ravel() / circlesize
py = 1. - px
idx = np.logical_and(px > 1. / circlesize, px < 1.)
entropy = - ( np.mean(px[idx] * np.log(px[idx])) + np.mean(py[idx] * np.log(py[idx])) )
entropystd = np.std(px[idx] * np.log(px[idx]) + py[idx] * np.log(py[idx]))
# Compute normalised lacunarity
lx = np.var(Y) / (np.mean(Y) ** 2) + 1
ly = np.var(1. - Y) / (np.mean(1. - Y) ** 2) + 1
# Roy et al, J. Struct. Geol. 2010
# Results
roylac.append((lx - 1.) / (1./np.mean(E) - 1.))
scaleent.append(entropy)
scaleentstd.append(entropystd)
# <codecell>
qstain = np.array([[.26451728, .5205347, .81183386], [.9199094, .29797825, .25489032], [.28947765, .80015373, .5253158]])
deconv = ski.img_as_float(color.separate_stains(transform.rescale(A, 0.25), np.linalg.inv(qstain)))
subveins1 = \
morphology.remove_small_objects(
filter.threshold_adaptive(
filter.gaussian_filter(
deconv[:, :, 2] / deconv[:, :, 0],
11),
250, offset = -0.13),
60)
subveins2 = \
morphology.remove_small_objects(
filter.threshold_adaptive(
filter.gaussian_filter(
maximum_filter(
deconv[:, :, 2] / deconv[:, :, 0],
5),
11),
250, offset = -0.13),
60)
veins = \
maximum_filter(
morphology.remove_small_objects(
binary_fill_holes(
morphology.binary_closing(
np.logical_or(subveins1, subveins2),
morphology.disk(25)),
),
250),
55)
rawinflammation = \
morphology.remove_small_objects(
filter.threshold_adaptive(
exposure.adjust_sigmoid(
filter.gaussian_filter(
exposure.equalize_adapthist(
exposure.rescale_intensity(
deconv[:, :, 1],
out_range = (0, 1)),
ntiles_y = 1),
5),
cutoff = 0.6),
75, offset = -0.12),
250)
inflammation = \
maximum_filter(
rawinflammation,
55)
# <codecell>
total = veins + inflammation
coloured = np.zeros_like(deconv)
coloured[:, :, 1] = veins
coloured[:, :, 2] = inflammation
labelled, regions = measure.label(total, return_num = True)
inflammationcount = 0
inflammationsize = []
for b in range(1, regions) :
if (inflammation * (labelled == b)).sum() / ((veins * (labelled == b)).sum() + 1) > 0.5 :
inflammationcount += 1
inflammationsize.append((rawinflammation * labelled == b).sum())
# <codecell>
regions
# <codecell>
io.imshow(A)
# <codecell>
io.imshow(inflammation)
plt.scatter([qq[i].centroid[1] for i in range(regions-1)], [qq[i].centroid[0] for i in range(regions-1)])
# <codecell>
pairwise.min(axis=0).mean()