-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcropImage
executable file
·197 lines (164 loc) · 6.46 KB
/
cropImage
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
#!/usr/bin/env python
# remove the necessity to have .py extension
from PIL import Image
import sys
import os.path
import numpy as np
import math
import matplotlib.pyplot as plt # Just so we can visually confirm we have the same images
option_handle_list = ['--cropByPosition']
option_unique_list = ['--info', '--help', '--verbose', '--cropByHistogram', '--centerDot']
options = {}
for option_handle in option_handle_list:
if option_handle in sys.argv:
options[option_handle[2:]] = sys.argv[sys.argv.index(option_handle) + 1]
else:
options[option_handle[2:]] = None
for option_handle in option_unique_list:
if option_handle in sys.argv:
options[option_handle[2:]] = True
else:
options[option_handle[2:]] = None
if options['info'] != None or options['help'] != None:
print("Function cropImage.")
print("USAGE : cropImage [imagePath] [options]")
print("")
print("")
print("options")
print(" --cropByPosition path: crop the image depending on x positions")
print(" --cropByHistogram path: crop the image on 128*128 patches depending on histogram")
exit()
if not os.path.exists(sys.argv[1]):
raise ValueError("Incorrect path, image path must be the first argument")
imagePath = sys.argv[1]
if options['verbose']:
np.set_printoptions(threshold=sys.maxsize) #writing entire data (not splitting) may consume time
img = Image.open(imagePath)
print("number of images found : ", img.n_frames)
images = []
for i in range(img.n_frames): #number of images
img.seek(i)
if options['verbose']:
print("----------- image " + str(i) + "-----------")
print("format : " + str(img.format))
print("size : " + str(img.size))
print("mode : " + str(img.mode))
npyImage = np.array(img)
images.append(npyImage)
imageNumber = 0 #id of image to treat
imageToTreat = images[imageNumber]
print(type(images[imageNumber]))
print(images[imageNumber], images[imageNumber].dtype)
print(len(images[imageNumber]), len(images[imageNumber][0]))
yColumns = int(len(images[imageNumber])/128)
xColumns = int(len(images[imageNumber][0])/128)
if options['cropByHistogram'] != None:
valuesImage = images[imageNumber].flatten()
max = np.amax(valuesImage)
min = np.amin(valuesImage)
print("Range :", min, max)
threshold = min + (max - min) / 10 #ignoring <10% values
for y in range(0, xColumns):
for x in range(0, yColumns):
save = False
temp = np.ndarray(shape=(128,128), dtype="uint16")
for i in range(y * 128, (y + 1) * 128 - 1 ):
for j in range(x * 128, (x + 1) * 128 - 1):
temp[i - y * 128][j - x * 128] = images[imageNumber][i][j]
if images[imageNumber][i][j] > threshold:
save = True
if save:
print("imagesToSave --> y:", y, " x:", x)
result.append(temp)
sqrt = math.ceil(math.sqrt(len(result)))
fig = plt.figure(figsize=(sqrt, sqrt))
for i in range(1, len(result) + 1):
fig.add_subplot(sqrt, sqrt, i)
plt.imshow(result[i - 1])
plt.show()
if options['cropByPosition'] != None:
pathHDF5 = options['cropByPosition']
import h5py
import math
sliceHeight = 40
if not os.path.exists(pathHDF5):
raise ValueError("Incorrect path, the path of an HDF5 file from picasso library must be added after the cropByHistogram option")
with h5py.File(pathHDF5, 'r') as f:
# List all groups
#print("Keys: %s" % f.keys())
a_group_key = list(f.keys())[0] #print("a_group_key: %s" % a_group_key)
# Get the data
data = list(f[a_group_key])
#format
dotPositions = []
for i in range(0, len(data)):
####################
## data[i] format ## obtained with the localize func of picasso https://github.com/jungmannlab/picasso
####################
# 0: n_frames
# 1: x
# 2: y
# 3: photons
# 4: sx
# 5: sy
# 6: bg
# 7: lpx
# 8: lpy
# 9: net_gradient
# 10: likelihood
# 11: iterations
while len(dotPositions) <= data[i][0]:
dotPositions.append([])
dotPositions[data[i][0]].append([data[i][1], data[i][2]])
if options['verbose']:
for i in range(0, len(dotPositions)):
print("dotPositions ", i, "len : ", len(dotPositions[i]))
print(dotPositions[i])
print()
imageResults = []
alreadyPrinted = [] # remember the alreadyPrinted slices
for i in dotPositions[imageNumber]:
x = int(i[0])
y = int(i[1])
newImage = np.ndarray(shape=(sliceHeight,512), dtype="uint16")
increment = 0
if options['centerDot']:
for yToGet in range(y - int(sliceHeight/2), y + int(sliceHeight/2)):
newImage[increment] = images[imageNumber][yToGet]
increment += 1
else:
begining = sliceHeight * math.trunc(y/sliceHeight)
end = sliceHeight * (math.trunc(y/sliceHeight) + 1)
if not begining in alreadyPrinted:
for yToGet in range(begining, end):
newImage[increment] = images[imageNumber][yToGet]
increment += 1
alreadyPrinted.append(begining)
imageResults.append(newImage)
fig = plt.figure(figsize=(len(imageResults), 1))
for i in range(1, len(imageResults) + 1):
fig.add_subplot(len(imageResults), 1, i)
plt.imshow(imageResults[i - 1])
plt.show()
# for indexY, valueX in enumerate(images[1]):
# if indexY < 128:
# for indexX, valueY in enumerate(images[1][indexY]):
# if indexX < 128:
# result[indexY][indexX] = valueY
# plt.imshow(result)
# plt.show()
#
# result = np.ndarray(shape=(128,128), dtype="uint16")
# for indexY, valueX in length(images[1]):
# if indexY > 127 and indexY < 256:
# for indexX, valueY in enumerate(images[1][indexY]):
# if indexX < 128:
# result[indexY - 128 ][indexX] = valueY
# plt.imshow(result)
# plt.show()
# sqrt = math.ceil(math.sqrt(img.n_frames))
# fig = plt.figure(figsize=(sqrt, sqrt))
# for i in range(1, img.n_frames +1):
# fig.add_subplot(sqrt, sqrt, i)
# plt.imshow(images[i - 1])
# plt.show()