marius10p commited on
Commit
5fe9f41
·
2 Parent(s): 76034ab d23bb1f

Merge branch 'main' of https://huggingface.co/spaces/mouseland/cellpose

Browse files
Files changed (2) hide show
  1. app.py +169 -76
  2. requirements.txt +1 -1
app.py CHANGED
@@ -9,8 +9,19 @@ import os, io, base64
9
  from PIL import Image
10
  from cellpose.io import imread, imsave
11
 
 
 
 
 
 
 
12
  # @title Data retrieval
13
- def download_weights():
 
 
 
 
 
14
  import os, requests
15
 
16
  fname = ['cpsam']
@@ -19,20 +30,24 @@ def download_weights():
19
 
20
  for j in range(len(url)):
21
  if not os.path.isfile(fname[j]):
22
- try:
23
- r = requests.get(url[j])
24
- except requests.ConnectionError:
25
- print("!!! Failed to download data !!!")
26
- else:
27
- if r.status_code != requests.codes.ok:
28
- print("!!! Failed to download data !!!")
29
- else:
30
- with open(fname[j], "wb") as fid:
31
- fid.write(r.content)
 
 
 
 
32
 
33
  try:
34
- download_weights()
35
- model = models.CellposeModel(gpu=True, pretrained_model="cpsam")
36
  except Exception as e:
37
  print(f"Error loading model: {e}")
38
  exit(1)
@@ -51,6 +66,7 @@ def plot_flows(y):
51
  return flow
52
 
53
  def plot_outlines(img, masks):
 
54
  outpix = []
55
  contours, hierarchy = cv2.findContours(masks.astype(np.int32), mode=cv2.RETR_FLOODFILL, method=cv2.CHAIN_APPROX_SIMPLE)
56
  for c in range(len(contours)):
@@ -94,7 +110,12 @@ def plot_outlines(img, masks):
94
  return pil_img
95
 
96
  def plot_overlay(img, masks):
97
- img = normalize99(img.astype(np.float32).mean(axis=-1))
 
 
 
 
 
98
  img -= img.min()
99
  img /= img.max()
100
  HSV = np.zeros((img.shape[0], img.shape[1], 3), np.float32)
@@ -146,66 +167,76 @@ def run_model_gpu1000(img):
146
  masks, flows, _ = model.eval(img)#, channels = [0,0])
147
  return masks, flows
148
 
149
- #@spaces.GPU(duration=10)
150
- def cellpose_segment(img_pil, resize = 400):
151
- img_input = imread(img_pil)
152
- #img_input = np.array(img_pil)
153
- img = image_resize(img_input, resize = resize)
154
-
155
- resize = np.max(img.shape)
156
- if resize<1000:
157
- masks, flows = run_model_gpu(img)
158
- elif resize < 5000:
159
- masks, flows = run_model_gpu60(img)
160
- elif resize < 20000:
161
- masks, flows = run_model_gpu240(img)
162
- else:
163
- raise ValueError("Image size must be less than 20,000")
164
-
 
 
 
 
 
 
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  #masks, flows, _ = model.eval(img, channels=[0,0])
167
  flows = flows[0]
168
  # masks = np.zeros(img.shape[:2])
169
  # flows = np.zeros_like(img)
170
 
171
  outpix = plot_outlines(img, masks)
172
- overlay = plot_overlay(img, masks)
173
-
174
- target_size = (img_input.shape[1], img_input.shape[0])
175
- if (target_size[0]!=img.shape[1] or target_size[1]!=img.shape[0]):
176
- # scale it back to keep the orignal size
177
- masks = cv2.resize(masks.astype('uint16'), target_size, interpolation=cv2.INTER_NEAREST).astype('uint16')
178
- #flows = cv2.resize(flows.astype('float32'), target_size).astype('uint8')
179
 
 
180
 
181
  #crand = .2 + .8 * np.random.rand(np.max(masks.flatten()).astype('int')+1,).astype('float32')
182
  #crand[0] = 0
183
 
184
- overlay = Image.fromarray(overlay)
185
  flows = Image.fromarray(flows)
186
 
187
  Ly, Lx = img.shape[:2]
188
- c = Lx
189
  outpix = outpix.resize((Lx, Ly), resample = Image.BICUBIC)
190
- overlay = overlay.resize((Lx, Ly), resample = Image.BICUBIC)
191
  flows = flows.resize((Lx, Ly), resample = Image.BICUBIC)
192
 
193
- #masks = Image.fromarray(255. * crand[masks])
194
- #pil_masks = Image.fromarray(masks.astype('int32'))
195
- #pil_masks.save(fname_mask)
196
-
197
- fname_out = os.path.splitext(img_pil)[0]+"_outlines.png"
198
- fname_masks = os.path.splitext(img_pil)[0]+"_masks.tif"
199
-
200
- imsave(fname_masks, masks)
201
-
202
-
203
  outpix.save(fname_out) #"outlines.png")
204
 
205
- b1 = gr.DownloadButton(visible=True, value = fname_masks)
 
 
 
 
 
 
206
  b2 = gr.DownloadButton(visible=True, value = fname_out) #"outlines.png")
207
 
208
- return outpix, overlay, flows, b1, b2
209
 
210
  # Gradio Interface
211
  #iface = gr.Interface(
@@ -221,41 +252,103 @@ def download_function():
221
  b2 = gr.DownloadButton("Download outline image as PNG", visible=False)
222
  return b1, b2
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  with gr.Blocks(title = "Hello",
225
  css=".gradio-container {background:purple;}") as demo:
226
 
 
227
  with gr.Row():
228
  with gr.Column(scale=2):
229
- gr.HTML("""<div style="font-family:'Times New Roman', 'Serif'; font-size:16pt; font-weight:bold; text-align:center; color:white;">Cellpose-SAM for cellular segmentation</div>""")
230
- gr.HTML("""<h4 style="color:white;">You may need to refresh/login for 5 minutes of free GPU compute/day. </h4>""")
231
- gr.HTML("""<h4 style="color:white;">"pip install cellpose" for full functionality. </h4>""")
232
-
233
- input_image = gr.Image(label = "Input image", type = "filepath")
 
 
234
 
235
  with gr.Row():
236
- resize = gr.Number(label = 'max resize', value = 400)
237
- send_btn = gr.Button("Run Cellpose-SAM")
238
-
239
- with gr.Row():
240
- down_btn = gr.DownloadButton("Download masks (TIF)", visible=False)
241
- down_btn2 = gr.DownloadButton("Download outlines (PNG)", visible=False)
242
-
243
- gr.HTML("""<a style="color:white;" href="https://github.com/MouseLand/cellpose" target="_blank">github page for cellpose</a>""")
244
- gr.HTML("""<a style="color:white;" href="https://github.com/MouseLand/cellpose" target="_blank">Cellpose-SAM paper</a>""")
245
-
 
 
 
 
 
 
246
 
247
- with gr.Column(scale=2):
248
- img_outlines = gr.Image(label = "Outlines", type = "pil", format = 'png') #, width = "50vw", height = "20vw")
249
- img_overlay = gr.Image(label = "Overlay", type = "pil", format = 'png') #, width = "50vw", height = "20vw")
250
- flows = gr.Image(label = "Cellpose flows", type = "pil", format = 'png') #, width = "50vw", height = "20vw")
251
- #masks = gr.Image(label = "Output image", type = "numpy")
252
-
 
 
253
 
254
- send_btn.click(fn=cellpose_segment, inputs=[input_image, resize], outputs=[img_outlines, img_overlay, flows, down_btn, down_btn2])
255
 
256
  #down_btn.click(download_function, None, [down_btn, down_btn2])
257
 
 
 
 
 
 
 
258
 
259
-
260
-
 
261
  demo.launch()
 
9
  from PIL import Image
10
  from cellpose.io import imread, imsave
11
 
12
+ from huggingface_hub import hf_hub_download
13
+
14
+ img = np.zeros((96, 128))
15
+ fp0 = "0.png"
16
+ imsave(fp0, img)
17
+
18
  # @title Data retrieval
19
+ def download_weights():
20
+ return hf_hub_download(repo_id="mouseland/cellpose-sam", filename="cpsam")
21
+
22
+ #os.system("wget -q https://huggingface.co/mouseland/cellpose-sam/resolve/main/cpsam")
23
+
24
+ def download_weights_old():
25
  import os, requests
26
 
27
  fname = ['cpsam']
 
30
 
31
  for j in range(len(url)):
32
  if not os.path.isfile(fname[j]):
33
+ ntries = 0
34
+ while ntries<10:
35
+ try:
36
+ r = requests.get(url[j])
37
+ except:
38
+ print("!!! Failed to download data !!!")
39
+ ntries += 1
40
+ print(ntries)
41
+
42
+ if r.status_code != requests.codes.ok:
43
+ print("!!! Failed to download data !!!")
44
+ else:
45
+ with open(fname[j], "wb") as fid:
46
+ fid.write(r.content)
47
 
48
  try:
49
+ fpath = download_weights()
50
+ model = models.CellposeModel(gpu=True, pretrained_model = fpath)
51
  except Exception as e:
52
  print(f"Error loading model: {e}")
53
  exit(1)
 
66
  return flow
67
 
68
  def plot_outlines(img, masks):
69
+ img = normalize99(img)
70
  outpix = []
71
  contours, hierarchy = cv2.findContours(masks.astype(np.int32), mode=cv2.RETR_FLOODFILL, method=cv2.CHAIN_APPROX_SIMPLE)
72
  for c in range(len(contours)):
 
110
  return pil_img
111
 
112
  def plot_overlay(img, masks):
113
+ if img.ndim>2:
114
+ img_gray = img.astype(np.float32).mean(axis=-1)
115
+ else:
116
+ img_gray = img.astype(np.float32)
117
+
118
+ img = normalize99(img_gray)
119
  img -= img.min()
120
  img /= img.max()
121
  HSV = np.zeros((img.shape[0], img.shape[1], 3), np.float32)
 
167
  masks, flows, _ = model.eval(img)#, channels = [0,0])
168
  return masks, flows
169
 
170
+
171
+ from zipfile import ZipFile
172
+ def cellpose_segment(filepath, resize = 1000):
173
+
174
+ zip_path = os.path.splitext(filepath[-1])[0]+"_masks.zip"
175
+ #zip_path = 'masks.zip'
176
+ with ZipFile(zip_path, 'w') as myzip:
177
+ for j in range((len(filepath))):
178
+ print(j)
179
+ img_input = imread(filepath[j])
180
+ #img_input = np.array(img_pil)
181
+ img = image_resize(img_input, resize = resize)
182
+
183
+ maxsize = np.max(img.shape)
184
+ if maxsize<1000:
185
+ masks, flows = run_model_gpu(img)
186
+ elif maxsize < 5000:
187
+ masks, flows = run_model_gpu60(img)
188
+ elif maxsize < 20000:
189
+ masks, flows = run_model_gpu240(img)
190
+ else:
191
+ raise ValueError("Image size must be less than 20,000")
192
 
193
+ target_size = (img_input.shape[1], img_input.shape[0])
194
+ if (target_size[0]!=img.shape[1] or target_size[1]!=img.shape[0]):
195
+ # scale it back to keep the orignal size
196
+ masks_rsz = cv2.resize(masks.astype('uint16'), target_size, interpolation=cv2.INTER_NEAREST).astype('uint16')
197
+ else:
198
+ masks_rsz = masks.copy()
199
+
200
+ fname_masks = os.path.splitext(filepath[j])[0]+"_masks.tif"
201
+ imsave(fname_masks, masks_rsz)
202
+
203
+ myzip.write(fname_masks, arcname = os.path.split(fname_masks)[-1])
204
+
205
+
206
  #masks, flows, _ = model.eval(img, channels=[0,0])
207
  flows = flows[0]
208
  # masks = np.zeros(img.shape[:2])
209
  # flows = np.zeros_like(img)
210
 
211
  outpix = plot_outlines(img, masks)
212
+ #overlay = plot_overlay(img, masks)
 
 
 
 
 
 
213
 
214
+
215
 
216
  #crand = .2 + .8 * np.random.rand(np.max(masks.flatten()).astype('int')+1,).astype('float32')
217
  #crand[0] = 0
218
 
219
+ #overlay = Image.fromarray(overlay)
220
  flows = Image.fromarray(flows)
221
 
222
  Ly, Lx = img.shape[:2]
 
223
  outpix = outpix.resize((Lx, Ly), resample = Image.BICUBIC)
224
+ #overlay = overlay.resize((Lx, Ly), resample = Image.BICUBIC)
225
  flows = flows.resize((Lx, Ly), resample = Image.BICUBIC)
226
 
227
+ fname_out = os.path.splitext(filepath[-1])[0]+"_outlines.png"
 
 
 
 
 
 
 
 
 
228
  outpix.save(fname_out) #"outlines.png")
229
 
230
+ fname_flows = os.path.splitext(filepath[-1])[0]+"_flows.png"
231
+ flows.save(fname_flows) #"outlines.png")
232
+
233
+ if len(filepath)>1:
234
+ b1 = gr.DownloadButton(visible=True, value = zip_path)
235
+ else:
236
+ b1 = gr.DownloadButton(visible=True, value = fname_masks)
237
  b2 = gr.DownloadButton(visible=True, value = fname_out) #"outlines.png")
238
 
239
+ return fname_out, fname_flows, b1, b2
240
 
241
  # Gradio Interface
242
  #iface = gr.Interface(
 
252
  b2 = gr.DownloadButton("Download outline image as PNG", visible=False)
253
  return b1, b2
254
 
255
+ def tif_view(filepath):
256
+ fpath, fext = os.path.splitext(filepath)
257
+ if fext in ['tiff', 'tif']:
258
+ img = imread(filepath[-1])
259
+ if img.ndim==2:
260
+ img = np.tile(img[:,:,np.newxis], [1,1,3])
261
+ elif img.ndim==3:
262
+ imin = np.argmin(img.shape)
263
+ if imin<2:
264
+ img = np.tranpose(img, [2, imin])
265
+ else:
266
+ raise ValueError("TIF cannot have more than three dimensions")
267
+
268
+ Ly, Lx, nchan = img.shape
269
+ imgi = np.zeros((Ly, Lx, 3))
270
+ nn = np.minimum(3, img.shape[-1])
271
+ imgi[:,:,:nn] = img[:,:,:nn]
272
+
273
+ #filepath = fpath+'.png'
274
+ imsave(filepath, imgi)
275
+ return filepath
276
+
277
+ def norm_path(filepath):
278
+ img = imread(filepath)
279
+ img = normalize99(img)
280
+ img = np.clip(img, 0, 1)
281
+ fpath, fext = os.path.splitext(filepath)
282
+ filepath = fpath +'.png'
283
+ pil_image = Image.fromarray((255. * img).astype(np.uint8))
284
+ pil_image.save(filepath)
285
+ #imsave(filepath, pil_image)
286
+ return filepath
287
+
288
+ def update_image(filepath):
289
+ for f in filepath:
290
+ f = tif_view(f)
291
+ filepath_show = norm_path(filepath[-1])
292
+ return filepath_show, filepath, fp0, fp0
293
+
294
+ def update_button(filepath):
295
+ filepath = tif_view(filepath)
296
+ filepath_show = norm_path(filepath)
297
+ return filepath_show, [filepath], fp0, fp0
298
+
299
  with gr.Blocks(title = "Hello",
300
  css=".gradio-container {background:purple;}") as demo:
301
 
302
+ #filepath = ""
303
  with gr.Row():
304
  with gr.Column(scale=2):
305
+ gr.HTML("""<div style="font-family:'Times New Roman', 'Serif'; font-size:20pt; font-weight:bold; text-align:center; color:white;">Cellpose-SAM for cellular
306
+ segmentation <a style="color:#cfe7fe; font-size:14pt;" href="https://github.com/MouseLand/cellpose" target="_blank">[paper]</a>
307
+ <a style="color:white; font-size:14pt;" href="https://github.com/MouseLand/cellpose" target="_blank">[github]</a>
308
+ </div>""")
309
+ gr.HTML("""<h4 style="color:white;">You may need to login/refresh for 5 minutes of free GPU compute per day (enough to process hundreds of images). </h4>""")
310
+
311
+ input_image = gr.Image(label = "Input", type = "filepath")
312
 
313
  with gr.Row():
314
+ with gr.Column(scale=1):
315
+ with gr.Row():
316
+ resize = gr.Number(label = 'max resize', value = 1000)
317
+ up_btn = gr.UploadButton("Multi-file upload (png, jpg, tif etc)", visible=True, file_count = "multiple")
318
+
319
+ #gr.HTML("""<h4 style="color:white;"> Note2: Only the first image of a tif will display the segmentations, but you can download segmentations for all planes. </h4>""")
320
+
321
+ with gr.Column(scale=1):
322
+ send_btn = gr.Button("Run Cellpose-SAM")
323
+ down_btn = gr.DownloadButton("Download masks (TIF)", visible=False)
324
+ down_btn2 = gr.DownloadButton("Download outlines (PNG)", visible=False)
325
+
326
+ with gr.Column(scale=2):
327
+ outlines = gr.Image(label = "Outlines", type = "filepath", format = 'png', value = fp0) #, width = "50vw", height = "20vw")
328
+ #img_overlay = gr.Image(label = "Overlay", type = "pil", format = 'png') #, width = "50vw", height = "20vw")
329
+ flows = gr.Image(label = "Cellpose flows", type = "filepath", format = 'png', value = fp0) #, width = "50vw", height = "20vw")
330
 
331
+
332
+ sample_list = []
333
+ for j in range(23):
334
+ sample_list.append("samples/img%0.2d.png"%j)
335
+
336
+ gr.Examples(sample_list, fn = update_button, inputs=input_image, outputs = [input_image, up_btn, outlines, flows], examples_per_page=25, label = "Click on an example to try it")
337
+ input_image.upload(update_button, input_image, [input_image, up_btn, outlines, flows])
338
+ up_btn.upload(update_image, up_btn, [input_image, up_btn, outlines, flows])
339
 
340
+ send_btn.click(cellpose_segment, [up_btn, resize], [outlines, flows, down_btn, down_btn2])
341
 
342
  #down_btn.click(download_function, None, [down_btn, down_btn2])
343
 
344
+ gr.HTML("""<h4 style="color:white;"> Notes:<br>
345
+ <li>you can load and process 2D multi-channel tifs.
346
+ <li>the smallest dimension of a tif --> channels
347
+ <li>you can load multiple files and download a zip of the segmentations
348
+ <li>install Cellpose-SAM locally for full functionality.
349
+ </h4>""")
350
 
351
+ # <li>the smallest dimension of a tif --> channels
352
+ # <li>you can load multiple files and download a zip of the segmentations
353
+
354
  demo.launch()
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
  gradio
2
- git+https://github.com/mouseland/cellpose_dev
3
  matplotlib
 
1
  gradio
2
+ git+https://github.com/MouseLand/cellpose_dev
3
  matplotlib