-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestApi.py
2296 lines (1718 loc) · 89.8 KB
/
RestApi.py
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
#=========================================================
#* HistoJS Demo - v1.0.0 | 2023
#=========================================================
#
# Github: https://github.com/Mmasoud1
# Description: A user interface for whole slide image channel design and analysis.
# It is based on DSA as backbone server.
#
#
# Coded by Mohamed Masoud ( [email protected] )
#
#=========================================================
#
#=========================================================
# Flask Rest Api
#=========================================================
#
#!env/bin/python
from __future__ import print_function, unicode_literals, absolute_import, division
from stardist.models import StarDist2D
from flask import Flask, request, Response, render_template, jsonify
from flask_cors import CORS
import json
import girder_client
import PIL
from PIL import Image, ImageFile
import os,sys,io
from io import BytesIO
import numpy as np
import re
import requests
from os import remove
import os
import glob
import h5py
import cv2
import base64
from csbdeep.utils import Path, normalize
from csbdeep.io import save_tiff_imagej_compatible
from stardist import random_label_cmap, _draw_polygons, export_imagej_rois
from sklearn.preprocessing import MinMaxScaler
from sklearn.manifold import TSNE
from skimage import data, img_as_float
from skimage import measure
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
from scipy.ndimage import find_objects
from scipy.spatial import Delaunay, ConvexHull, convex_hull_plot_2d
from skimage import measure
from skimage.measure import label, regionprops, approximate_polygon
from collections import defaultdict
import itertools
import pandas as pd
import math
import psutil
import gc as garbageCollect
import codecs
from tqdm import tqdm
import matplotlib.pyplot as plt
import seaborn as sns
#UMAP Dim Reduction
import umap.umap_ as umap
#LDA Dim Reduction
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
#PCA Dim Reduction
from sklearn.decomposition import PCA
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
ImageFile.LOAD_TRUNCATED_IMAGES = True
# To avoid PIL.Image.DecompressionBombError:
# Image size (xxxxxxxx pixels) exceeds limit of 178956970 pixels
PIL.Image.MAX_IMAGE_PIXELS = None
MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/appready')
def appready():
return "true"
def alignImages(im1, im2, alignName, outputFolder, im1colored, enhanceFlag):
# This follows OpenCV example...https://www.learnopencv.com/image-alignment-feature-based-using-opencv-c-python/
# Convert images to grayscale
if (enhanceFlag==0):
im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) # image to align
im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) # Ref image
# Detect ORB features and compute descriptors.
orb = cv2.ORB_create(MAX_FEATURES)
if (enhanceFlag==0):
keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)
else:
keypoints1, descriptors1 = orb.detectAndCompute(im1, None)
keypoints2, descriptors2 = orb.detectAndCompute(im2, None)
# Match features.
matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
matches = matcher.match(descriptors1, descriptors2, None)
# Sort matches by score
matches.sort(key=lambda x: x.distance, reverse=False)
# Remove not so good matches
numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
matches = matches[:numGoodMatches]
# Draw top matches
imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
cv2.imwrite(outputFolder + alignName + "matches.jpg", imMatches)
# Extract location of good matches
points1 = np.zeros((len(matches), 2), dtype=np.float32)
points2 = np.zeros((len(matches), 2), dtype=np.float32)
for i, match in enumerate(matches):
points1[i, :] = keypoints1[match.queryIdx].pt
points2[i, :] = keypoints2[match.trainIdx].pt
# Find homography
h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)
# Use homography
if(enhanceFlag==0):
height, width, channels = im2.shape
im1Reg = cv2.warpPerspective(im1, h, (width, height))
else:
height, width = im2.shape
im1Reg = cv2.warpPerspective(im1colored, h, (width, height))
return im1Reg, h
@app.route('/imageRegistration')
def imageRegistration():
xreffilename = request.args.get('refName', 0)
ximgfilename = request.args.get('imgToRegName', 0)
xoutFolder = request.args.get('outFolder', 0)
xvpWidth = request.args.get('vpWidth', 0, type=int)
xvpHeight = request.args.get('vpHeight', 0, type=int)
xenhancement = request.args.get('enhance', 0, type=int)
# print("************************************************************")
if (os.path.isdir(xoutFolder)==False):
os.mkdir(xoutFolder)
if (os.path.isdir(xoutFolder)==True):
if ((os.path.isfile(xoutFolder+xreffilename)==True) and (os.path.isfile(xoutFolder+ximgfilename)==True)):
# Read reference image
print("Reading reference image : ", xreffilename)
imReference = cv2.imread(xoutFolder+ xreffilename, cv2.IMREAD_COLOR);
# Read image to be aligned
print("Reading image to align : ", ximgfilename);
im = cv2.imread(xoutFolder+ ximgfilename, cv2.IMREAD_COLOR);
print("Aligning images ...")
# Registered image will be restored in imReg.
# The estimated homography will be stored in h.
if(xenhancement==0):
imReg, h = alignImages(im, imReference, ximgfilename.split('.')[0], xoutFolder, im, xenhancement)
else:
imReferenceGray = cv2.cvtColor(imReference, cv2.COLOR_BGR2GRAY)
blurRef = cv2.GaussianBlur(imReferenceGray,(5,5),0)
retRef,imReference_OTSU = cv2.threshold(blurRef,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite(xoutFolder+"imReference_OTSU.jpg", imReference_OTSU)
imGray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
blurIm = cv2.GaussianBlur(imGray,(5,5),0)
retIm,im_OTSU = cv2.threshold(blurIm,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite(xoutFolder+"im2reg_OTSU.jpg", im_OTSU)
imReg, h = alignImages(im_OTSU, imReference_OTSU, ximgfilename.split('.')[0], xoutFolder,im, xenhancement)
# Write aligned image to disk.
outFilename = ximgfilename.split('.')[0]+"aligned.jpg"
print("Saving aligned image : ", outFilename);
cv2.imwrite(xoutFolder+outFilename, imReg)
# Print estimated homography
print("Estimated homography : \n", h)
if os.path.isfile(xoutFolder+outFilename):
DicData=[];
Dic={'outFilename':'','Hemography':'','outWidth':'','outHeight':'','mse':'', 'psnr':''} ;
Dic['outFilename']=outFilename
Dic['Hemography']=h.tolist()
Dic['outWidth']=imReg.shape[1]
Dic['outHeight']=imReg.shape[0]
Dic['mse']=measure.compare_mse(imReference,imReg)
Dic['psnr']=measure.compare_psnr(imReference,imReg)
DicData.append(Dic.copy())
return Response(json.dumps(DicData))
else:
return "failed"
def mse(x, y):
return np.linalg.norm(x - y)
@app.route('/imageQuality')
def imageQuality():
xreffilename = request.args.get('refImage', 0)
ximgfilename = request.args.get('imgToAss', 0)
xoutFolder = request.args.get('outFolder', 0)
if (os.path.isdir(xoutFolder)==False):
os.mkdir(xoutFolder)
if (os.path.isdir(xoutFolder)==True):
if ((os.path.isfile(xoutFolder+xreffilename)==True) and (os.path.isfile(xoutFolder+ximgfilename)==True)):
# Read reference image
print("Reading reference image : ", xreffilename)
imReference = cv2.imread(xoutFolder+ xreffilename, cv2.IMREAD_COLOR)
# Read image to assesse
print("Reading image to Assessment : ", ximgfilename);
im = cv2.imread(xoutFolder+ ximgfilename, cv2.IMREAD_COLOR)
width1, height1, depth1 = imReference.shape
width2, height2, depth2 = im.shape
ssim_value = measure.compare_ssim(imReference, im,
data_range=imReference.max() - imReference.min(),multichannel=True)
psnr_value = measure.compare_psnr(imReference,im)
nrmse_value = measure.compare_nrmse(imReference,im)
mse_value = measure.compare_mse(imReference,im)
return str(psnr_value)
@app.route('/saveLayer')
def saveLayer():
xindex = request.args.get('index', 0)
xdata_url = request.args.get('imageContent',0)
xoutFolder = request.args.get('outFolder', 0)
ximgfilename = request.args.get('imgName', 0)
xmode = request.args.get('mode', 0)
if (os.path.isdir(xoutFolder)==False):
os.mkdir(xoutFolder)
xoutFilename = ximgfilename+"layer"+xindex+".txt"
print(xoutFolder+xoutFilename)
file=open(xoutFolder+xoutFilename,xmode)
file.write(xdata_url)
file.close()
if os.path.isfile(xoutFolder+xoutFilename):
return xoutFilename+" saved"
else:
return xoutFilename+" failed"
@app.route('/saveRegOffsets')
def saveRegOffsets():
xoutFolder = request.args.get('outFolder', 0)
xoffsets = request.args.get('offsets', 0)
xfilename = request.args.get('name', 0)
xmode = request.args.get('mode', 0)
if (os.path.isdir(xoutFolder)==False):
os.mkdir(xoutFolder)
xoutFilename = xfilename+"-Offsets"+".txt"
if (os.path.isfile(xoutFolder+xoutFilename)==True):
os.remove(xoutFolder+xoutFilename)
file=open(xoutFolder+xoutFilename,xmode)
file.write(xoffsets)
file.close()
if os.path.isfile(xoutFolder+xoutFilename):
return "saved"
else:
return "failed"
@app.route('/preprocessSavedLayer')
def preprocessSavedLayer():
# try:
xindex = request.args.get('index', 0)
xoutFolder = request.args.get('outFolder', 0)
ximgfilename = request.args.get('imgName', 0)
if (os.path.isdir(xoutFolder)==False):
os.mkdir(xoutFolder)
outFilename = ximgfilename+"layer"+xindex+".txt"
if (os.path.isfile(xoutFolder+outFilename)==True):
file=open(xoutFolder+outFilename,"r")
xdata_url=file.read()
file.close()
os.remove(xoutFolder+outFilename) # remove txt file
content = xdata_url.split(';')[1]
image_encoded = content.split(',')[1]
image_encoded_modified=image_encoded.replace(' ', '+')
# pngImageContent = base64.decodebytes(image_encoded_modified.encode('utf-8')) // for python version3 only
# pngImageContent = image_encoded_modified.decode('base64')
pngImageContent = base64.b64decode(image_encoded_modified.encode('utf-8'))
outFilename = ximgfilename+"layer"+xindex+".png"
print("Saving image : ", outFilename);
with open(xoutFolder+outFilename, 'wb') as f:
f.write(pngImageContent)
f.close()
img = cv2.imread(xoutFolder+ outFilename, cv2.IMREAD_UNCHANGED)
# print("-------------------------------------------------------------------------------------------------------------------")
# print("-------------------------------------------------------------------------------------------------------------------")
if((img.shape[0]!=0) and (img.shape[1]!=0)):
y,x = img[:,:,3].nonzero() # get the nonzero alpha coordinates
minx = np.min(x)
miny = np.min(y)
maxx = np.max(x)
maxy = np.max(y)
cropImg = img[miny:maxy, minx:maxx]
image_without_alpha = cropImg[:,:,:3]
cv2.imwrite(xoutFolder+outFilename, image_without_alpha)
return outFilename+" Alpha removed successfully"
else:
print ('fail')
return "fail"
@app.route('/readJsonFile')
def readJsonFile():
file_name = request.args.get('filename', 0)
out_folder = request.args.get('outfolder', 0)
path_to_file = os.path.join(out_folder, file_name)
print("Please wait while reading JSON file .....", path_to_file)
if (os.path.isfile(path_to_file)):
file = open(path_to_file, "r")
file_contents = file.read()
file.close()
return file_contents
else:
return jsonify("notExist")
# @app.route('/readBoundaries')
# def readBoundaries():
# file_name = request.args.get('filename', 0)
# out_folder = request.args.get('outfolder', 0)
# path_to_file = os.path.join(out_folder, file_name)
# print("Please wait while reading boundaries file .....", path_to_file)
# if (os.path.isfile(path_to_file)):
# file = open(out_folder + file_name, "r")
# boundaries = file.read()
# file.close()
# return boundaries
# else:
# return "notExist"
#-------------------------------------------------------------------------------#
############################## Boundaries from Dapi #############################
#-------------------------------------------------------------------------------#
# Scale contour, resize it smaller or larger to include for the example the cytoplasom
def scale_contour(cnt, scale):
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
cnt_norm = cnt - [cx, cy]
cnt_scaled = cnt_norm * scale
cnt_scaled = cnt_scaled + [cx, cy]
cnt_scaled = cnt_scaled.astype(np.int32)
return cnt_scaled
# source code inspired from cellpose
def masks_to_outlines(masks):
if masks.ndim > 3 or masks.ndim < 2:
raise ValueError('masks_to_outlines takes 2D or 3D array, not %dD array'%masks.ndim)
outlines = np.zeros(masks.shape, np.bool)
if masks.ndim==3:
for i in range(masks.shape[0]):
outlines[i] = masks_to_outlines(masks[i])
return outlines
else:
slices = find_objects(masks.astype(int))
for i,si in enumerate(slices):
if si is not None:
sr,sc = si
mask = (masks[sr, sc] == (i+1)).astype(np.uint8)
contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
pvc, pvr = np.concatenate(contours[-2], axis=0).squeeze().T
vr, vc = pvr + sr.start, pvc + sc.start
outlines[vr, vc] = 1
return outlines
def normalize_image(img):
"""can be used in case of csbdeep.utils normalize failed """
img = (img - img.min()) / (img.max() - img.min())
return img
@app.route('/createBoundariesFromDapiChannel')
def createBoundariesFromDapiChannel():
#Flag to determine which approach to extract boundaries from mask ie. contour based or regionprops based
# if contour approach is False then regionprops will be used
is_boundary_extraction_contours_based = request.args.get('isBoundaryExtractionContoursBased', type=bool)
print("Boundary extraction is contours based: ", is_boundary_extraction_contours_based)
# if remove outliers is need
is_remove_outliers_required = request.args.get('isRemoveOutliersRequired', type=bool)
print("Remove outliers is required: ", is_remove_outliers_required)
# if removing all outliers of all morphologies are need
all_features_outliers_considered = request.args.get('allFeaturesOutliersConsidered', type=int)
print("Remove all Features outliers is required: ", all_features_outliers_considered)
reset_boundaries_label_after_outlier_filter = request.args.get('resetBoundaryLabelAfterOutlierFilter', type=bool)
print("Reset boundaries label after outlier filter: ", reset_boundaries_label_after_outlier_filter)
approximation_requested = request.args.get('contourApproxRequest', type=bool)
print("approximation_requested: ", approximation_requested)
use_95_05_percentile = request.args.get('use95_05Percentile', type=bool)
percentile_lower = float(request.args.get('percentileLower', 0))
percentile_upper = float(request.args.get('percentileUpper', 0))
print("use_95_05_percentile requested: ", use_95_05_percentile)
if use_95_05_percentile:
print("percentile_lower requested: ", percentile_lower)
print("percentile_upper requested: ", percentile_upper)
file_name = request.args.get('filename', 0)
out_folder = request.args.get('outfolder', 0)
base_url = request.args.get('baseUrl', 0)
item_id = request.args.get('itemId', 0)
api_key = request.args.get('apiKey', 0)
dapi_ch_index = request.args.get('dapiChannelIdx', type=int)
print("dapi_ch_index: ", dapi_ch_index)
contour_scale_factor = float(request.args.get('contourScaleFactor', 0))
print("contour scale factor: ", contour_scale_factor)
contour_approx_factor = float(request.args.get('nuclContourApproxFactor', 0))
print("contour approximation factor: ", contour_approx_factor)
invalid_nucl_area_threshold = request.args.get('invalidNuclAreaThreshold', type=int)
print("invalid nucl area threshold: ", invalid_nucl_area_threshold)
# is_boundary_extraction_contours_based = False
# is_remove_outliers_required = True
# all_features_outliers_considered = False
# reset_boundaries_label_after_outlier_filter = True
raw_contours_file_name = file_name.split(".json")[0] + '_raw_contours.json'
# cells_label_file_name = file_name.split(".json")[0] + '_labels.json'
if (not os.path.isfile(out_folder + raw_contours_file_name)) or (not is_boundary_extraction_contours_based):
print("Please wait while creating boundaries from Dapi Channel ................")
request_url = "item/" + item_id + "/tiles/region?units=base_pixels&exact=false&frame=" + str(dapi_ch_index) + "&encoding=JPEG&jpegQuality=95&jpegSubsampling=0"
gc = girder_client.GirderClient(apiUrl = base_url)
if( api_key ):
gc.authenticate(apiKey = api_key)
girder_response = gc.get(request_url, jsonResp=False)
else:
girder_response = requests.get(base_url + request_url)
dapi_channel_raw = Image.open(io.BytesIO(girder_response.content))
dapi_channel = np.array(dapi_channel_raw)
# Check or Convert to grey scale channel
dapi_channel_gray = []
if len(dapi_channel.shape) > 2 :
dapi_channel_gray = cv2.cvtColor(dapi_channel, cv2.COLOR_BGR2GRAY)
dapi_channel = dapi_channel_gray
n_channel = 1 if dapi_channel.ndim == 2 else dapi_channel.shape[-1]
axis_norm = (0,1) # normalize channels independently
if n_channel > 1:
print("Normalizing image channels %s." % ('jointly' if axis_norm is None or 2 in axis_norm else 'independently'))
# Normalize channel
dapi_channel_norm = normalize(dapi_channel, 1,99.8, axis=axis_norm)
print("Dapi normalization done..")
# creates a pretrained model
model = StarDist2D.from_pretrained('2D_versatile_fluo')
# Get labels and polys for the image/ DAPI channel
dapi_channel_labels, dapi_channel_polys = model.predict_instances_big(dapi_channel_norm, axes='YX', block_size=4096, min_overlap=128, context=128, n_tiles=(4,4))
print("Dapi labels prediction done..")
## Convert starDist polys to contours
### Method #1 to convert (faster)
print("Convert dapi channel polys to contours in progress..")
contours = []
for poly in tqdm(dapi_channel_polys['coord']):
merge_coord = list(zip(poly[1], poly[0]))
contours.append(np.around(merge_coord).astype(int))
print("Total number of converted dapi channel polys--> contours : {}".format(len(contours)))
# save contours array as Json
if not (os.path.isdir(out_folder)):
os.makedirs(out_folder)
contours_arr = np.asarray(contours)
contours_list = contours_arr.tolist()
json.dump(contours_list, codecs.open(out_folder + raw_contours_file_name, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4)
# save labels array as Json
# contours_arr = np.asarray(contours)
# contours_list = contours_arr.tolist()
# json.dump(contours_list, codecs.open(out_folder + raw_contours_file_name, 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4)
else:
# if is_boundary_extraction_contours_based:
print("Wait reading raw contours from saved json file")
contours_text = codecs.open(out_folder + raw_contours_file_name, 'r', encoding='utf-8').read()
contours_json = json.loads(contours_text)
contours = list(np.array(contours_json))
# else:
# print("Wait reading labels from saved json file")
# labels_text = codecs.open(out_folder + cells_label_file_name, 'r', encoding='utf-8').read()
# labels_json = json.loads(labels_text)
# dapi_channel_labels = list(np.array(labels_json))
# if there is a need to scale countour to enlarge or shrink it
if contour_scale_factor != 1:
print("Contours scaling in progress..")
scaled_contours = []
for cont in tqdm(contours):
scaled_contours.append(scale_contour(cont, contour_scale_factor))
contours = scaled_contours
#check if contours need reverse order
# mask_height = dapi_channel.shape[0]
# mask_width = dapi_channel.shape[1]
# contours_reverse_flag = True
# polygon = Polygon([(0, 0), (0, mask_width/2), (mask_height/2, mask_width/2), (mask_height/2, 0)])
# for vertex in contours[0]:
# point = Point(vertex[0][0], vertex[0][1])
# if polygon.contains(point) :
# contours_reverse_flag = False
# if contours_reverse_flag :
# contours.reverse()
# Get contours/Regions properties
maskBoundariesData = []
idx = 1
if all_features_outliers_considered:
features_to_remove_outliers = ['area', 'eccentricity', 'extent', 'major_axis_length', 'minor_axis_length', 'orientation', 'perimeter', 'solidity']
else:
features_to_remove_outliers = ['area', 'perimeter']
# features_to_remove_outliers = ['area']
if is_boundary_extraction_contours_based:
nearest_decimal = 2
invalid_contour_num = 0
# Conversion loop
for contour in tqdm(contours):
spxBoundaries = []
if approximation_requested :
approx = cv2.approxPolyDP(contour, contour_approx_factor * cv2.arcLength(contour, True), True)
cnt = approx
else:
cnt = contour
# check for valid vertex
invalid_vertex = False
if len(cnt) > 2 :
for vertex in cnt:
spxBoundaries.append(str(vertex[0][0]) + ',' + str(vertex[0][1]))
if (vertex[0][0] < 0) or (vertex[0][1] < 0):
invalid_vertex = True
if invalid_vertex:
invalid_contour_num += 1
continue
else:
continue
# compute the center of the contour
M = cv2.moments(contour)
if M["m00"] != 0:
x_cent = int(M["m10"] / M["m00"])
y_cent = int(M["m01"] / M["m00"])
else:
# set values as what you need in the situation
#print(cnt)
# x_cent, y_cent = 0, 0
continue
# maskBoundariesData.append({"label": idx, "x_cent": x_cent, "y_cent": y_cent, "spxBoundaries":' '.join(spxBoundaries) })
# idx += 1
# contour area
area = round(cv2.contourArea(contour), nearest_decimal)
if area < invalid_nucl_area_threshold :
continue
# contour perimeter
perimeter = round(cv2.arcLength(contour,True), nearest_decimal)
#Extent is the ratio of contour area to bounding rectangle area.
x,y,w,h = cv2.boundingRect(contour)
rect_area = w*h
extent = round( float(area)/rect_area, nearest_decimal)
#calculating Solidity and eccentricity
#Solidity is the ratio of contour area to its convex hull area.
## Usually Tumor has higher solidity value than normal tissue
# If the eccentricity is one, it will be a straight line and if it is zero, it will be a perfect circle
try:
## For Solidity we need to calculate hull area first
hull = cv2.convexHull(contour)
hull_area = cv2.contourArea(hull)
## center, axis_length and orientation of ellipse
(center, axes, orientation) = cv2.fitEllipse(contour)
except:
#print("An exception occurred during calculating eccentricity")
continue
solidity = round( float(area)/hull_area, nearest_decimal)
major_axis_length = round( max(axes), nearest_decimal)
minor_axis_length = round( min(axes), nearest_decimal)
## eccentricity = sqrt( 1 - (ma/MA)^2) --- ma= minor axis --- MA= major axis
eccentricity = round( np.sqrt(1-(minor_axis_length/major_axis_length)**2), nearest_decimal)
# area, eccentricity, solidity, extent , euler_number, perimeter, major_axis_length, minor_axis_length, centroid, orientation
maskBoundariesData.append({"label": idx, "area": area, "eccentricity": eccentricity, "orientation": round(orientation, nearest_decimal), "perimeter" : perimeter, "extent": extent, "solidity": solidity, "major_axis_length": major_axis_length, "minor_axis_length": minor_axis_length, "x_cent": x_cent, "y_cent": y_cent, "neighbors": None, "spxBoundaries":' '.join(spxBoundaries) })
idx += 1
print(' Num of invalid contour found: {}'.format(invalid_contour_num))
#------------------------------------------------------------------------------------------------------#
#-----------------------------------------Region based boundaries -------------------------------------#
#------------------------------------------------------------------------------------------------------#
# boundaries are regionprops based, but the points can be very large, need approximation
else:
print("regionprops based cell morphology calculations: ")
print("Please wait ...")
props = measure.regionprops(dapi_channel_labels)
invalid_region_num = 0
invalid_area_num = 0
# Conversion loop
for prop in tqdm(props):
spxBoundaries = []
try:
# to get the boundaries, get convex hull of region points (prop.coords is area points not perimeter point)
hull = ConvexHull(prop.coords)
hull_indices = hull.vertices
hull_pts = prop.coords[hull_indices, :]
except:
continue
if approximation_requested :
approx = approximate_polygon(hull_pts, tolerance = 1.5)
else:
approx = hull_pts
invalid_vertex = False
for vertex in approx:
spxBoundaries.append(str(vertex[1]) + ',' + str(vertex[0]))
if (vertex[1] < 0) or (vertex[0] < 0):
invalid_vertex = True
if invalid_vertex:
invalid_region_num += 1
continue
if prop.area < invalid_nucl_area_threshold:
invalid_area_num += 1
continue
maskBoundariesData.append({"label": idx, "area": prop.area, "eccentricity": prop.eccentricity, "solidity": prop.solidity, "extent": prop.extent, "perimeter": prop.perimeter, "major_axis_length": prop.major_axis_length, "minor_axis_length": prop.minor_axis_length, "orientation": math.degrees(prop.orientation), "x_cent": round(prop.centroid[1]), "y_cent": round(prop.centroid[0]), "spxBoundaries":' '.join(spxBoundaries) })
idx += 1
print(' Num of invalid region found: {}'.format(invalid_region_num))
print(' Num of invalid areas found: {}'.format(invalid_area_num))
if len(maskBoundariesData):
# if remove outliers option is set
if is_remove_outliers_required:
print("Wait for outliers to remove ...")
df = pd.DataFrame.from_dict(maskBoundariesData)
df_after_filter = df
for feature in features_to_remove_outliers:
if use_95_05_percentile:
P_lower = df[feature].quantile(percentile_lower)
P_upper = df[feature].quantile(percentile_upper)
filter = (df_after_filter[feature] >= P_lower) & (df_after_filter[feature] <= P_upper)
else:
Q1 = df[feature].quantile(0.25)
Q3 = df[feature].quantile(0.75)
IQR = Q3 - Q1 #IQR is interquartile range.
filter = (df_after_filter[feature] >= Q1 - 1.5 * IQR) & (df_after_filter[feature] <= Q3 + 1.5 *IQR)
df_after_filter = df_after_filter.loc[filter]
maskBoundariesData_update = df_after_filter.to_dict('records')
# reset labels to start from 1 to len(maskBoundariesData_update
if reset_boundaries_label_after_outlier_filter:
for index, item in enumerate(maskBoundariesData_update):
item['label'] = index +1
else:
maskBoundariesData_update = maskBoundariesData
# convert x_cent and y_cent to array of points
print("Wait while calculating neighbors ...")
all_points = [];
for contour in maskBoundariesData_update:
all_points.append([contour['x_cent'], contour['y_cent']]);
tri = Delaunay(all_points)
neiList = defaultdict(set)
for p in tri.vertices:
for i,j in itertools.combinations(p,2):
neiList[i].add(j)
neiList[j].add(i)
for key in sorted(neiList.keys()):
neighbor_array = list(neiList[key])
for index in range(len(neighbor_array)):
neighbor_array[index] += 1
# maskBoundariesData_update[key]['neighbors'] = neighbor_array
# we need to convert to np.arrary and then to list again to overcome the issue of :
# TypeError: Object of type int64 is not JSON serializable
maskBoundariesData_update[key]['neighbors'] =(np.array(neighbor_array, dtype=np.int32)).tolist()
# Verify the created file
print('Total num of extracted boundaries :',len(maskBoundariesData_update))
print('Total num of contours :',len(contours))
# Create Json file
if not (os.path.isdir(out_folder)):
os.makedirs(out_folder)
with open(out_folder + file_name, 'w') as f:
json.dump(maskBoundariesData_update, f)
if (os.path.isfile(out_folder + file_name)):
return "Created successfully"
else:
return "Failed"
#-------------------------------------------------------------------------------#
############################## Boundaries from Mask #############################
#-------------------------------------------------------------------------------#
@app.route('/createBoundariesFromMask')
def createBoundariesFromMask():
approximation_requested = request.args.get('contourApproxRequest', 0, type=bool)
print("approximation_requested ", approximation_requested)
file_name = request.args.get('filename', 0)
out_folder = request.args.get('outfolder', 0)
base_url = request.args.get('baseUrl', 0)
item_id = request.args.get('itemId', 0)
api_key = request.args.get('apiKey', 0)
print("Please wait while creating boundaries from mask ................")
request_url = "/item/" + item_id + "/tiles/region?units=base_pixels&exact=false&encoding=JPEG&jpegQuality=95&jpegSubsampling=0"
gc = girder_client.GirderClient(apiUrl = base_url)
if( api_key ):
gc.authenticate(apiKey = api_key)
girder_response = gc.get(request_url, jsonResp=False)
else:
girder_response = requests.get(base_url + request_url)
cellMaskImage = Image.open(io.BytesIO(girder_response.content))
cellMaskImage_array = np.array(cellMaskImage)
# Check or Convert to grey scale mask
cellMaskImage_gray = []
if len(cellMaskImage_array.shape) > 2 :
cellMaskImage_gray = cv2.cvtColor(cellMaskImage_array, cv2.COLOR_BGR2GRAY)
cellMaskImage_array = cellMaskImage_gray
# Check or Convert to binary mask
if len( np.unique( cellMaskImage_array ) ) > 2 :
(thresh, cellMaskImage_bw) = cv2.threshold(cellMaskImage_array, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
else :
if len( np.unique( cellMaskImage_array ) ) == 2 :
if cellMaskImage_array.max() == 255 and cellMaskImage_array.min() == 0:
cellMaskImage_bw = cellMaskImage_array;
else:
return "Not a Valid Mask"
else:
return "Not a Valid Mask"
# Use cv2.RETR_EXTERNAL neglect internal contours (i.e. contour inside contour)
contours, _ = cv2.findContours(cellMaskImage_bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
mask_height = cellMaskImage_array.shape[0]
mask_width = cellMaskImage_array.shape[1]
#check if contours need reverse order
contours_reverse_flag = True
polygon = Polygon([(0, 0), (0, mask_width/2), (mask_height/2, mask_width/2), (mask_height/2, 0)])
for vertex in contours[0]:
point = Point(vertex[0][0], vertex[0][1])
if polygon.contains(point) :
contours_reverse_flag = False
if contours_reverse_flag :
contours.reverse()
maskBoundariesData = []
idx = 1
num_of_invalid_contours = 0
# Conversion loop
for contour in contours:
spxBoundaries = []
# check whether contours approximation is requested, this can reduced output JSON file around 60%
if approximation_requested :
approximated_contour = cv2.approxPolyDP(contour, 0.009 * cv2.arcLength(contour, True), True)
cnt = approximated_contour
else:
cnt = contour
# check for valid contours that has at least 3 points
if len(cnt) > 2 :
for vertex in cnt:
spxBoundaries.append(str(vertex[0][0])+','+str(vertex[0][1]))
else:
num_of_invalid_contours += 1
continue
# compute the center of the contour
M = cv2.moments(cnt)
if M["m00"] != 0:
x_cent = int(M["m10"] / M["m00"])
y_cent = int(M["m01"] / M["m00"])
else:
# set values as what you need in the situation
# x_cent, y_cent = 0, 0
num_of_invalid_contours += 1
continue
maskBoundariesData.append({"label": idx, "x_cent": x_cent, "y_cent": y_cent, "spxBoundaries":' '.join(spxBoundaries) })
idx += 1
# Create Json file
if not (os.path.isdir(out_folder)):
os.makedirs(out_folder)
with open(out_folder + file_name, 'w') as f:
json.dump(maskBoundariesData, f)
print(' Number of invalid contours : ', num_of_invalid_contours)
if (os.path.isfile(out_folder + file_name)):
return "Created successfully"
else:
return "Failed"
# return Response(json.dumps(maskBoundariesData))
def find_bbox(points):
xpx = []
ypx = []
box = []
for px in points.split(" "):
xpx.append(int(px.split(",")[0]))
ypx.append(int(px.split(",")[1]))
xpx.sort();
ypx.sort();
xpx_min = xpx[0];
xpx_max = xpx[len(xpx)-1];
ypx_min = ypx[0];
ypx_max = ypx[len(ypx)-1];
xWidth = xpx_max-xpx_min;
yHeight = ypx_max-ypx_min;
box.append({"left": xpx_min, "top": ypx_min, "width": xWidth , "height": yHeight})
return box
def is_grey_scale(image):
if len(image.shape) > 2:
if (np.array_equal(image[:,:,0], image[:,:,1])) and (np.array_equal(image[:,:,0], image[:,:,2])):
return True
else:
return False
else:
return True
def str_to_array(points):
pair_points = []
for px in points.split(" "):
if sys.version_info[0] < 3:
# For python 2
pair_points.append(map(int, px.split(",")))
else:
# For python 3
pair_points.append(list(map(int, px.split(","))))
return pair_points
@app.route('/createDapiCellsMorphStatData')
def createDapiCellsMorphStatData():
print("Find statistics of morphology features e.g. area,..")
dapi_morph_stats_file_name = request.args.get('dapi_morph_stats_file', 0)
item_features_folder = request.args.get('item_features_folder', 0)
boundaries_file_name = request.args.get('boundaries_file', 0)
boundaries_folder = request.args.get('boundaries_folder', 0)
basic_morph_features_string= request.args.get('morph_feature_names_arr', 0)
path_to_dapi_morph_stats_file = os.path.join(item_features_folder, dapi_morph_stats_file_name)
path_to_boundaries_file = os.path.join(boundaries_folder, boundaries_file_name)
# read cell morphology file having cells boundary, area, extent .. etc
df_cell_morphology = pd.read_json(path_to_boundaries_file)
# Find statistical data
morphology_states = df_cell_morphology.describe()
# basic_morph_features should be ['area', 'eccentricity', 'extent', 'orientation', 'solidity', 'major_axis_length', 'minor_axis_length']
# Refere to cellMorphFeatureList with mainParametersV3.js file for more details
basic_morph_features = json.loads(basic_morph_features_string)
all_basic_morph_feat_States = {}
for morph_feature in basic_morph_features:
all_basic_morph_feat_States[morph_feature] = {"mean" : morphology_states[morph_feature]['mean'],
"std" : morphology_states[morph_feature]['std'],
"min" : morphology_states[morph_feature]['min'],
"25%" : morphology_states[morph_feature]['25%'],
"50%" : morphology_states[morph_feature]['50%'],