CompactionAnalyzer 1.0.1__tar.gz → 1.0.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer/CompactionFunctions.py +292 -162
  2. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer/QtShortCuts.py +527 -58
  3. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer/StructureTensor.py +10 -3
  4. compactionanalyzer-1.0.7/CompactionAnalyzer/__init__.py +7 -0
  5. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer/plotting.py +59 -21
  6. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer/utilities.py +7 -5
  7. compactionanalyzer-1.0.7/CompactionAnalyzer.egg-info/PKG-INFO +27 -0
  8. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer.egg-info/SOURCES.txt +1 -1
  9. compactionanalyzer-1.0.7/CompactionAnalyzer.egg-info/requires.txt +10 -0
  10. compactionanalyzer-1.0.7/PKG-INFO +27 -0
  11. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/README.md +78 -20
  12. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/setup.py +8 -5
  13. CompactionAnalyzer-1.0.1/CompactionAnalyzer/__init__.py +0 -7
  14. CompactionAnalyzer-1.0.1/CompactionAnalyzer.egg-info/PKG-INFO +0 -14
  15. CompactionAnalyzer-1.0.1/CompactionAnalyzer.egg-info/requires.txt +0 -5
  16. CompactionAnalyzer-1.0.1/PKG-INFO +0 -14
  17. /CompactionAnalyzer-1.0.1/CompactionAnalyzer/GUI.py → /compactionanalyzer-1.0.7/CompactionAnalyzer/GUI_old_use_saenopy_instead.py +0 -0
  18. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer/QExtendedGraphicsView.py +0 -0
  19. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer.egg-info/dependency_links.txt +0 -0
  20. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/CompactionAnalyzer.egg-info/top_level.txt +0 -0
  21. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/LICENSE +0 -0
  22. {CompactionAnalyzer-1.0.1 → compactionanalyzer-1.0.7}/setup.cfg +0 -0
@@ -2,12 +2,17 @@ import numpy as np
2
2
  from skimage import io
3
3
  from PIL import Image
4
4
  from skimage.filters import gaussian, threshold_otsu, threshold_yen
5
- import scipy.ndimage.morphology as scipy_morph
6
- import scipy.ndimage.measurements as scipy_meas
7
5
  from skimage.morphology import remove_small_objects
8
6
  import imageio
9
7
  from skimage import color
10
- from scipy.ndimage.morphology import distance_transform_edt
8
+ try:
9
+ from scipy.ndimage import distance_transform_edt
10
+ import scipy.ndimage as scipy_morph
11
+ import scipy.ndimage as scipy_meas
12
+ except ImportError:
13
+ from scipy.ndimage.morphology import distance_transform_edt
14
+ import scipy.ndimage.morphology as scipy_morph
15
+ import scipy.ndimage.measurements as scipy_meas
11
16
  import matplotlib.pyplot as plt
12
17
  import os
13
18
  import pandas as pd
@@ -69,6 +74,15 @@ def custom_mask(img,show_segmentation=True):
69
74
  dict: Dictionary with keys: mask, radius, centroid (x/y)
70
75
  """
71
76
  from roipoly import RoiPoly
77
+ import matplotlib
78
+
79
+ # switch backend for roipoly
80
+ try:
81
+ mpl_backend = matplotlib.get_backend()
82
+ matplotlib.use('Qt5Agg')
83
+ except:
84
+ print ("Switched to Qt5Agg Backend for Roipoly")
85
+
72
86
  # need to install RoiPoly package via pip to use this function
73
87
  height = img.shape[0]
74
88
  width = img.shape[1]
@@ -93,7 +107,15 @@ def custom_mask(img,show_segmentation=True):
93
107
  # if show_segmentation:
94
108
  # plt.figure()
95
109
  # plt.subplot(121), plt.imshow(img)
96
- # plt.subplot(122), plt.imshow(mask)
110
+ # plt.subplot(122), plt.imshow(mask)
111
+
112
+ # switch to original backend
113
+ try:
114
+ matplotlib.use(mpl_backend)
115
+ print ("Switched Back")
116
+ except:
117
+ print ("Could not switched back")
118
+
97
119
  return {'mask': mask, 'radius': radius, 'centroid': (cx, cy)}
98
120
 
99
121
  def regional_maxima(img):
@@ -124,7 +146,10 @@ def segment_cell(img, thres=1, seg_gaus1 = 0.5, seg_gaus2=100, seg_iter=1,show_s
124
146
  height = img.shape[0]
125
147
  width = img.shape[1]
126
148
 
127
-
149
+ ## if 3 channels convert to grey
150
+ if len(img.shape) == 3 :
151
+ img = color.rgb2gray(img)
152
+
128
153
  # local gaussian (or single gaussian if gaus2 == None)
129
154
  if seg_gaus2 is not None:
130
155
  img = np.abs(gaussian(img, sigma=seg_gaus1) - gaussian(img, sigma=seg_gaus2))
@@ -195,6 +220,24 @@ def segment_cell(img, thres=1, seg_gaus1 = 0.5, seg_gaus2=100, seg_iter=1,show_s
195
220
  return {'mask': mask, 'radius': radius, 'centroid': (cx, cy)}
196
221
 
197
222
 
223
+ def create_centered_circle(image_shape):
224
+ # Extract the height and width of the image
225
+ height, width = image_shape[:2]
226
+ # Calculate the center of the image
227
+ center_y, center_x = height // 2, width // 2
228
+ # Calculate the radius of the circle (1/4 of the image height or width)
229
+ radius = min(height, width) // 10
230
+ # Create a 2D array of zeros (background)
231
+ circle_array = np.zeros((height, width), dtype=int)
232
+ # Iterate over each point in the 2D array
233
+ for y in range(height):
234
+ for x in range(width):
235
+ # Calculate the distance from the center
236
+ distance = np.sqrt((y - center_y) ** 2 + (x - center_x) ** 2)
237
+ # If the distance is less than or equal to the radius, set it to 1 (circle)
238
+ if distance <= radius:
239
+ circle_array[y, x] = 1
240
+ return circle_array
198
241
 
199
242
 
200
243
  def StuctureAnalysisMain(fiber_list,
@@ -204,10 +247,11 @@ def StuctureAnalysisMain(fiber_list,
204
247
  sigma_tensor = None , # sigma of applied gauss filter / window for structure tensor analysis in px
205
248
  # should be in the order of the objects to analyze !!
206
249
  # 7 um for collagen
207
- edge = 40 , # Cutt of pixels at the edge since values at the border cannot be trusted
250
+ edge = 15 , # Cutt of pixels at the edge since values at the border cannot be trusted
208
251
  segmention_thres = 1.0 , # for cell segemetntion, thres 1 equals normal otsu threshold , user also can specify gaus1 + gaus2 in segmentation if needed
209
252
  seg_gaus1=0.5, seg_gaus2 = 100 , # 2 gaus filters used as bandpassfilter for local contrast enhancement; For seg_gaus2 = None a single gauss filter is applied
210
253
  max_dist = None, # optional: specify the maximal distance around cell center for analysis (in px)
254
+ min_dist = None, # optional: specify the minimals distance around cell center for analysis (in px)
211
255
  regional_max_correction = True,# background correction using regional maxima approach
212
256
  show_segmentation = False , # display the segmentation output
213
257
  sigma_first_blur = 0.5 , # slight first bluring of whole image before appplying the structure tensor
@@ -216,15 +260,24 @@ def StuctureAnalysisMain(fiber_list,
216
260
  manual_segmention = False , # segmentation of mask by manual clicking the cell outline
217
261
  plotting = True , # creates and saves individual figures additionally to the excel files
218
262
  dpi = 200 , # resolution of figures
219
- SaveNumpy = False , # saves numpy arrays for later analysis - can create large data files
263
+ SaveNumpy = True , # saves numpy arrays for later analysis
264
+ SaveExcel = True , # saves Excel files for later analysis
220
265
  norm1=1,norm2 = 99 , # contrast spreading for input images between norm1- and norm2-percentile; values below norm1-percentile are set to zero and
221
266
  # values above norm2-percentile are set to 1
267
+ ### use norm1= 0,norm2 = 100 if no contras enhancement desired
222
268
  seg_invert=False, # if segmentation is inverted dark objects are detected inseated of bright objects
223
269
  seg_iter = 1, # number of repetitions of binary closing, dilation and filling holes steps
224
270
  segmention_method="otsu", # use "otsu", "entropy" or "yen" as segmentation method
225
271
  segmention_min_area = 1000, # small bjects below this px-area are removed during cell segmentation
226
272
  load_segmentation = False, # if True enter the path of the segementation.npy - file in path_seg
227
- path_seg = None): # to load a mask
273
+ path_seg = None, # to load a mask
274
+ ignore_cell_outline=False, # if True the cell area is not set to nan and orientation are calculted everywhere - still the cell center is calculated from segmention
275
+
276
+
277
+ mode_saenopy=False): # only used for the Saenopy Version to return data files directly after single run
278
+
279
+
280
+
228
281
  """
229
282
  Main analysis
230
283
 
@@ -239,8 +292,16 @@ def StuctureAnalysisMain(fiber_list,
239
292
  None.
240
293
 
241
294
  """
242
- plt.ioff()
243
- # plt.ion()
295
+ # plt.ioff()
296
+ # plt.ion()
297
+
298
+ # if no cell images are specified we conduct the analyis on the full image
299
+ # for this, we create dummy images of an artificial cell and set ignore_cell_outline to True
300
+ # Might be usefull to look at quantities such as fiber coherency or angle towards x-axis
301
+ if cell_list == None:
302
+ ignore_cell_outline= True
303
+ dummy_cell = create_centered_circle(imageio.v2.imread(fiber_list[0]).shape)
304
+
244
305
 
245
306
  # if not specified use 7um for tensor analysis and 5um shells
246
307
  if not sigma_tensor:
@@ -268,30 +329,34 @@ def StuctureAnalysisMain(fiber_list,
268
329
  'SaveNumpy': [SaveNumpy], 'norm1': [norm1], 'norm2': [norm2],
269
330
  'seg_invert': [seg_invert], 'seg_iter': [seg_iter], 'segmention_method': [segmention_method],
270
331
  'load_segmentation': [load_segmentation], 'path_seg': [path_seg],
271
- 'max_dist': [max_dist]
332
+ 'max_dist': [max_dist], 'min_dist': [min_dist]
272
333
 
273
334
  },
274
335
  'Data' : {'fiber_list': [fiber_list], 'cell_list': [cell_list], 'out_list': [out_list]}
275
336
  }
276
337
  with open(os.path.join(out_list[n],"parameters.yml"), 'w') as yaml_file:
277
338
  yaml.dump(dict_file, yaml_file, default_flow_style=False)
278
-
279
339
 
280
- # load images
281
- im_cell = imageio.imread(cell_list[n]) #color.rgb2gray(..)
282
- im_fiber = imageio.imread(fiber_list[n]) #color.rgb2gray()
340
+ # load images
341
+ im_fiber = imageio.v2.imread(fiber_list[n]) #color.rgb2gray()
342
+ if cell_list == None:
343
+ im_cell = dummy_cell
344
+ else:
345
+ im_cell = imageio.v2.imread(cell_list[n])
346
+
283
347
 
284
348
  ## if 3 channels convert to grey
285
- if len(im_cell.shape) == 3 :
349
+ if len(im_cell.shape) == 3 :
286
350
  im_cell = color.rgb2gray(im_cell)
287
351
  if len(im_fiber.shape) == 3 :
288
- im_fiber = color.rgb2gray(im_fiber)
289
-
352
+ im_fiber = color.rgb2gray(im_fiber)
353
+
354
+
290
355
  # # applying normalizing/ contrast spreading
291
356
  im_cell_n = normalize(im_cell, norm1, norm2)
292
357
  im_fiber_n = normalize(im_fiber, norm1, norm2)
293
358
  im_fiber_g = gaussian(im_fiber_n, sigma=sigma_first_blur) # blur fiber image slightly (test with local gauss - similar)
294
-
359
+
295
360
 
296
361
  # segment cell (either manual or automatically)
297
362
  if manual_segmention==True:
@@ -308,20 +373,30 @@ def StuctureAnalysisMain(fiber_list,
308
373
  # center of the new cropped image (to avoid edge effects)
309
374
  center_small = (segmention["centroid"][0]-edge,segmention["centroid"][1]-edge)
310
375
 
311
- # set segmention mask to nan to avoid effects within cell (maybe not needed if signal below cell makes sense)
312
- im_fiber_g_forstructure = im_fiber_g.copy()
313
- im_fiber_g_forstructure[segmention["mask"]] = np.nan
314
-
376
+
377
+ ## do not set cell area to nan and but only use center from segmention if activaed
378
+ if ignore_cell_outline is True:
379
+ im_fiber_g_forstructure = im_fiber_g.copy()
380
+ else:
381
+ # set segmention mask to nan to avoid effects within cell (maybe not needed if signal below cell makes sense)
382
+ im_fiber_g_forstructure = im_fiber_g.copy()
383
+ im_fiber_g_forstructure[segmention["mask"]] = np.nan
384
+
385
+
386
+
315
387
  """
316
388
  Structure tensor
317
389
  """
318
390
  # Structure Tensor Orientation
319
391
  # get structure tensor
320
392
  ori, max_evec, min_evec, max_eval, min_eval = analyze_local(im_fiber_g_forstructure, sigma=sigma_tensor, size=0, filter_type="gaussian")
393
+
321
394
  # cut off edges as specified
322
395
  if edge != 0:
323
396
  ori, max_evec, min_evec, max_eval, min_eval = ori[edge:-edge,edge:-edge], max_evec[edge:-edge,edge:-edge], min_evec[edge:-edge,edge:-edge], \
324
397
  max_eval[edge:-edge,edge:-edge], min_eval[edge:-edge,edge:-edge]
398
+
399
+
325
400
  """
326
401
  coordinates
327
402
  """
@@ -334,31 +409,32 @@ def StuctureAnalysisMain(fiber_list,
334
409
  dx_norm = (dx/distance)
335
410
  dy_norm = (dy/distance)
336
411
  dist_surface = distance_transform_edt(~segmention["mask"])[edge:-edge,edge:-edge] # dist to surface
337
-
338
-
412
+ # calculate an angle without the deviation/reference to the cell position
413
+ angle_no_reference = ((np.arctan2(min_evec[:,:,0],min_evec[:,:,1])*360/(2*np.pi))%180)-90 # -90 to +90° towards x-axis
414
+
415
+
339
416
  """
340
417
  total image analysis
341
418
  """
342
- # Angular deviation from orietation to center vector -
419
+ # Angular deviation from orietation to center vector (projection to only have positive deviation angle values since negative/positive deviation does not matter here)
343
420
  angle_dev = np.arccos(np.abs(dx_norm * min_evec[:,:,0] + dy_norm*min_evec[:,:,1])) * 360/(2*np.pi)
344
- # calculate oreination from angle_dev since they are normal distributed and np.abs((dx_norm * min_evec[:,:,0] + dy_norm*min_evec[:,:,1])) is not
345
- orientation_dev_01 = angle_dev/90
346
- # orientation_dev_01 = np.abs((dx_norm * min_evec[:,:,0] + dy_norm*min_evec[:,:,1]))
347
- orientation_dev = -(2*orientation_dev_01-1) # norm from -1 to 1 ; changed sign
348
-
421
+ ## compute the orientation
422
+ orientation_dev = 1 - (2 * np.arccos(np.abs(dx_norm * min_evec[:,:,0] + dy_norm*min_evec[:,:,1]))/ (0.5* np.pi))
423
+
424
+
349
425
  ### set values to nan if max distance is specified
350
426
  ## for following analysis then only orientation within a certtain distance to the cell are used
351
427
  if max_dist:
352
- angle_dev[distance>=max_dist] = np.nan
353
- ori[distance>=max_dist] = np.nan
354
- angle[distance>=max_dist] = np.nan # also for angular evaluation
428
+ angle_dev[distance>max_dist] = np.nan
429
+ ori[distance>max_dist] = np.nan
430
+ angle[distance>max_dist] = np.nan # also for angular evaluation
355
431
 
356
- # weighting by coherence
357
- angle_dev_weighted = (angle_dev * ori) / np.nanmean(ori) # no angle values anymore (stretched due weights) but the mean later is again an angle
358
- orientation_dev_weighted_01 = ((orientation_dev_01 * ori) / np.nanmean(ori))
359
- orientation_dev_weighted = -(2 *orientation_dev_weighted_01 - 1)
360
-
361
-
432
+ if min_dist:
433
+ angle_dev[distance<min_dist] = np.nan
434
+ ori[distance<min_dist] = np.nan
435
+ angle[distance<max_dist] = np.nan # also for angular evaluation
436
+
437
+
362
438
  # weighting by coherence and image intensity
363
439
  im_fiber_g = im_fiber_g[edge:-edge,edge:-edge]
364
440
  # could also use non filtered image
@@ -366,14 +442,18 @@ def StuctureAnalysisMain(fiber_list,
366
442
  # use a threshold in the intensity image// only coherence and orientation vectors
367
443
  # corresponding to pixels in the intesity iamage above a threshold are considered.
368
444
  weight_image = gaussian(im_fiber_g,sigma=15)
445
+
446
+ # construct weighted array so that the mean value of these arrays later
447
+ # result in the weighted average of these
448
+ # weight by coherency
449
+ angle_dev_weighted = (angle_dev * ori) / np.nanmean(ori)
450
+ orientation_dev_weighted = (orientation_dev * ori) / np.nanmean(ori)
451
+ # weight by coherency & intensity
369
452
  angle_dev_weighted2 = (angle_dev_weighted *weight_image) / np.nanmean(weight_image)
370
- orientation_dev_weighted2_01 = (orientation_dev_01 *weight_image*ori) / np.nanmean(weight_image*ori)
371
- orientation_dev_weighted2 = -(2 * orientation_dev_weighted2_01 - 1)
372
-
373
- # also weighting the coherency like this
453
+ orientation_dev_weighted2 = (orientation_dev *weight_image*ori) / np.nanmean(weight_image*ori)
454
+ # weighting coherency by intensity
374
455
  ori_weight2 = (ori * weight_image) / np.nanmean(weight_image)
375
-
376
-
456
+
377
457
  # GRADIENT towards center
378
458
  grad_y = np.gradient(im_fiber_g, axis=0)
379
459
  grad_x = np.gradient(im_fiber_g, axis=1)
@@ -394,9 +474,7 @@ def StuctureAnalysisMain(fiber_list,
394
474
  alpha_dev_total1 = np.nanmean(angle_dev[(~segmention["mask"][edge:-edge,edge:-edge])])
395
475
  alpha_dev_total2 = np.nanmean(angle_dev_weighted[(~segmention["mask"][edge:-edge, edge:-edge])])
396
476
  alpha_dev_total3 = np.nanmean(angle_dev_weighted2[(~segmention["mask"][edge:-edge, edge:-edge])])
397
- # cos_dev_total1 = np.nanmean(np.cos(2*angle_dev[(~segmention["mask"][edge:-edge, edge:-edge])]*np.pi/180))
398
- # cos_dev_total2 = np.nanmean(np.cos(2*angle_dev_weighted[(~segmention["mask"][edge:-edge, edge:-edge])]*np.pi/180))
399
- # cos_dev_total3 = np.nanmean(np.cos(2*angle_dev_weighted2[(~segmention["mask"][edge:-edge, edge:-edge])]*np.pi/180))
477
+
400
478
  cos_dev_total1 = np.nanmean(orientation_dev[(~segmention["mask"][edge:-edge,edge:-edge]) ])
401
479
  cos_dev_total2 = np.nanmean(orientation_dev_weighted[(~segmention["mask"][edge:-edge,edge:-edge]) ])
402
480
  cos_dev_total3 = np.nanmean(orientation_dev_weighted2[(~segmention["mask"][edge:-edge,edge:-edge]) ])
@@ -420,7 +498,8 @@ def StuctureAnalysisMain(fiber_list,
420
498
  results_total['Orientation (weighted by intensity and coherency)'].append(cos_dev_total3)
421
499
 
422
500
  excel_total = pd.DataFrame.from_dict(results_total)
423
- excel_total.to_excel(os.path.join(out_list[n],"results_total.xlsx"))
501
+ if SaveExcel:
502
+ excel_total.to_excel(os.path.join(out_list[n],"results_total.xlsx"))
424
503
 
425
504
 
426
505
  """
@@ -475,14 +554,18 @@ def StuctureAnalysisMain(fiber_list,
475
554
 
476
555
  # create excel sheet with results for angle analysis
477
556
  excel_angles= pd.DataFrame.from_dict(results_angle)
478
- excel_angles.to_excel(os.path.join(out_list[n],"results_angles.xlsx"))
479
-
557
+ if SaveExcel:
558
+ excel_angles.to_excel(os.path.join(out_list[n],"results_angles.xlsx"))
480
559
 
560
+
481
561
  """
482
562
  Distance Evaluation
483
563
  """
484
564
 
485
- # initialize result dictionary
565
+
566
+ # def distance_analysis(shells,shell_width,dist_surface,scale,angle_dev, ori, orientation_dev, weight_image,im_fiber_g):
567
+
568
+ # initialize result dictionary
486
569
  results_distance = {'Shell_mid (px)': [], 'Shell_mid (µm)': [], 'Intensity (accumulated)': [],
487
570
  'Intensity (individual)': [], 'Intensity Norm (individual)': [],
488
571
  'Intensity Norm (accumulated)': [], 'Angle (accumulated)': [], 'Angle (individual)': [], 'Angle (individual-weightInt)': [],
@@ -494,7 +577,7 @@ def StuctureAnalysisMain(fiber_list,
494
577
  'Angle disttocenter (accumulated)': [], 'Angle disttocenter (individual)': [],
495
578
  'Orientation disttocenter (accumulated)': [], 'Orientation disttocenter (individual)': [],
496
579
  'Angle disttocenter (individual)': []
497
- }
580
+ }
498
581
 
499
582
  mask_shells = {'Mask_shell': [], 'Mask_shell_center': [] }
500
583
  # shell distances
@@ -527,7 +610,7 @@ def StuctureAnalysisMain(fiber_list,
527
610
  results_distance['Orientation (individual-weightInt)'].append(np.nanmean(orientation_dev[mask_shell]*ori[mask_shell]*weight_image[mask_shell]/np.nanmean(ori[mask_shell]*weight_image[mask_shell]) ))
528
611
 
529
612
 
530
- # mean intensity
613
+ # mean intensity
531
614
  results_distance['Intensity (accumulated)'].append(np.nanmean(im_fiber_g[mask_shell_lower])) # accumulation of lower shells
532
615
  results_distance['Intensity (individual)'].append(np.nanmean(im_fiber_g[mask_shell]) ) # exclusively in certain shell
533
616
 
@@ -561,135 +644,161 @@ def StuctureAnalysisMain(fiber_list,
561
644
  results_distance['Intensity Norm disttocenter (accumulated)'].extend(list(norm_accum_int_c) )
562
645
  # create excel sheet with results for angle analysis
563
646
  excel_distance = pd.DataFrame.from_dict(results_distance)
564
- excel_distance.to_excel(os.path.join(out_list[n],"results_distance.xlsx"))
647
+ if SaveExcel:
648
+ excel_distance.to_excel(os.path.join(out_list[n],"results_distance.xlsx"))
565
649
 
566
-
567
- # Halflife values - Leave for now..
568
- # # Calculate value where ntensity drops 25%
569
- # distintdrop = np.abs(np.array(results_distance['Intensity Norm (individual)'])-0.75)
570
- # # distance where int drops to 75%
571
- # halflife_int = midofshells[np.where(distintdrop == np.nanmin(distintdrop))[1]]
572
- # # if decrease is not within range (minimum equals last value) then set to nan
573
- # if halflife_int == midofshells[-1]:
574
- # halflife_int = np.nan
575
- # # # Calculate value where orientation drops to 75% within maxorientation(min) to 45° (random) range
576
- # # difference to 45 degree instead of min-max range
577
- # # calculate halflife of maximal orientation over distance
578
- # # difference to 45 degree for all
579
- # diffdist = np.array(dist_angle_individ)-45
580
- # # maximal orientation
581
- # diffmax = np.nanmin(diffdist)
582
- # diffmax_pos = np.where(diffmax==diffdist)[0][0]
583
- # # difference angle drops to 75%
584
- # diff2 = np.abs(diffdist-(0.75*diffmax))
585
- # diff2[:diffmax_pos] = np.nan # only look at distances on the right side /further out
586
- # halflife_ori = midofshells[np.where(diff2 == np.nanmin(diff2))]
587
- # # if decrease is not within range (minimum equals last value) then set to nan
588
- # if halflife_ori == midofshells[-1]:
589
- # halflife_ori = np.nan
590
- # try:
591
- # np.savetxt(os.path.join(out_list[n],"meanangle_within10shells.txt"), [dist_angle_accum[9]])
592
- # except:
593
- # pass
650
+
594
651
 
595
652
  if SaveNumpy:
596
653
  #create output folder if not existing
597
- numpy_out = os.path.join(out_list[n], r"NumpyArrays" )
654
+ numpy_out = os.path.join(out_list[n], "NumpyArrays" )
655
+ print (numpy_out)
598
656
  if not os.path.exists(numpy_out):
599
657
  os.makedirs(numpy_out)
600
-
601
- np.save(os.path.join(numpy_out, "segmention.npy" ),segmention)
602
- np.save(os.path.join(numpy_out, "AngleMap.npy" ),angle_dev )
603
- np.save(os.path.join(numpy_out, "AngleMap(weight_int).npy" ),angle_dev_weighted)
604
- np.save(os.path.join(numpy_out, "AngleMap(weight_int_coh).npy"),angle_dev_weighted2 )
658
+ # save data array all with the size of the evaluated arrays
659
+ # that are "edge" - pixels smaller to get rid of boundary artefacts
660
+ np.save(os.path.join(numpy_out, "segmention.npy" ),segmention["mask"][edge:-edge,edge:-edge])
661
+ np.save(os.path.join(numpy_out, "AngleDeviationMap.npy" ),angle_dev )
662
+ #np.save(os.path.join(numpy_out, "AngleMap(weight_int).npy" ),angle_dev_weighted)
663
+ np.save(os.path.join(numpy_out, "AngleDeviationMap(weight_int_coh).npy"),angle_dev_weighted2 )
664
+ np.save(os.path.join(numpy_out, "AngleMap_NoReference.npy"), angle_no_reference )
605
665
  np.save(os.path.join(numpy_out, "OrientationMap.npy" ),orientation_dev )
606
- np.save(os.path.join(numpy_out, "OrientationMap_weight_int.npy" ),orientation_dev_weighted)
666
+ #np.save(os.path.join(numpy_out, "OrientationMap_weight_int.npy" ),orientation_dev_weighted)
607
667
  np.save(os.path.join(numpy_out, "OrientationMap_weight_intcoh.npy" ),orientation_dev_weighted2 )
608
668
  np.save(os.path.join(numpy_out, "FiberImageCrop.npy" ),normalize(im_fiber_n[edge:-edge,edge:-edge]) )
609
669
  np.save(os.path.join(numpy_out, "CoherencyMap.npy" ),ori )
610
- np.save(os.path.join(numpy_out, "CoherencyMap(weighted_int).npy" ),ori_weight2)
670
+ #np.save(os.path.join(numpy_out, "CoherencyMap(weighted_int).npy" ),ori_weight2)
611
671
  np.save(os.path.join(numpy_out, "Vector_min_ax0.npy"),min_evec[:,:,0])
612
672
  np.save(os.path.join(numpy_out, "Vector_min_ax1.npy"),min_evec[:,:,1])
613
- np.save(os.path.join(numpy_out, "mask_surface_shells.npy"),mask_shells['Mask_shell'])
614
- np.save(os.path.join(numpy_out, "mask_spherical_shells.npy"),mask_shells['Mask_shell_center'])
615
-
616
-
617
-
618
-
673
+ np.save(os.path.join(numpy_out, "center.npy"),center_small)
674
+ #np.save(os.path.join(numpy_out, "mask_surface_shells.npy"),mask_shells['Mask_shell'])
675
+ #np.save(os.path.join(numpy_out, "mask_spherical_shells.npy"),mask_shells['Mask_shell_center'])
676
+
677
+ # check the shapes --> everything is the same format
678
+ # print(segmention["mask"][edge:-edge,edge:-edge].shape)
679
+ # print(orientation_dev.shape)
680
+ # print(normalize(im_fiber_n[edge:-edge,edge:-edge]).shape)
681
+ # print(angle_no_reference.shape)
682
+
683
+
619
684
  """
620
- Plott results
685
+ Plotting results
621
686
  """
622
687
 
623
688
  if plotting:
624
689
  #create output folder if not existing
625
690
  figures = os.path.join(out_list[n],"Figures")
691
+ print (figures)
626
692
  if not os.path.exists(figures):
627
693
  os.makedirs(figures)
628
-
629
- # plot orientation and angle deviation maps together with orientation structure
630
- plot_angle_dev(angle_map = angle_dev,
631
- vec0=min_evec[:,:,0] ,vec1=min_evec[:,:,1] ,coherency_map=ori,
632
- path_png= os.path.join(figures,"Angle_deviation.png"),label="Angle Deviation",dpi=dpi,cmap="viridis_r")
633
- plot_angle_dev(angle_map = angle_dev_weighted2,
634
- vec0=min_evec[:,:,0] ,vec1=min_evec[:,:,1] ,coherency_map=ori,
635
- path_png= os.path.join(figures,"Angle_deviation_weighted.png"),label="Angle Deviation",dpi=dpi,cmap="viridis_r")
636
- plot_angle_dev(angle_map = orientation_dev_weighted2 ,
637
- vec0=min_evec[:,:,0] ,vec1=min_evec[:,:,1] ,coherency_map=ori,
638
- path_png= os.path.join(figures,"Orientation_weighted.png"),label="Orientation",dpi=dpi,cmap="viridis")
639
- plot_angle_dev(angle_map = orientation_dev,
640
- vec0=min_evec[:,:,0] ,vec1=min_evec[:,:,1] ,coherency_map=ori,
641
- path_png= os.path.join(figures,"Orientation.png"),label="Orientation",dpi=dpi,cmap="viridis")
642
- plt.close("all")
643
- # pure coherency and pure orientation
644
- plot_coherency(ori,path_png= os.path.join(figures,"coherency_noquiver.png"))
645
- plot_coherency(orientation_dev_weighted2,
646
- path_png= os.path.join(figures,"Orientation_weighted_noquiver.png"),
647
- label="Orientation",dpi=dpi)
694
+
695
+ plot_angle_dev(angle_map = orientation_dev, vmin=-1,vmax=1,
696
+ vec0=min_evec[:,:,0] ,vec1=min_evec[:,:,1] ,coherency_map=ori,
697
+ path_png= os.path.join(figures,"Orientation.png"),label="Orientation",dpi=dpi,cmap="coolwarm")
698
+
699
+
700
+
701
+ if cell_list == None:
702
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
703
+ None,
704
+ angle_no_reference, cmap_angle="gist_rainbow",
705
+ path_png= os.path.join(figures,"Angle_NoReference_overlay_nocell.png"),
706
+ label="Angle (x-axis)",dpi=dpi,
707
+ # ,cmap_cell="Greys_r",cmap_fiber="Greys_r", ### use default values here
708
+ # cmap_angle="viridis", alpha_ori =0.8, alpha_cell = 0.4, alpha_fiber = 0.4,
709
+ omin=-90, omax=90,
710
+ scale=scale)
711
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
712
+ None,
713
+ ori, cmap_angle="turbo",
714
+ path_png= os.path.join(figures,"Coherency_overlay_nocell.png"),
715
+ label="Coherency",dpi=dpi,
716
+ # ,cmap_cell="Greys_r",cmap_fiber="Greys_r", ### use default values here
717
+ # cmap_angle="viridis", alpha_ori =0.8, alpha_cell = 0.4, alpha_fiber = 0.4,
718
+ omin=0, omax=1,scale=scale)
719
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
720
+ im_cell_n[edge:-edge,edge:-edge],
721
+ orientation_dev, cmap_angle="coolwarm",
722
+ path_png= os.path.join(figures,"Orientation_overlay.png"),
723
+ label="Orientation",dpi=dpi,
724
+ omin=-1, omax=1,scale=scale)
725
+
726
+ else:
727
+ ### more fancy overlay plot of cell & fiber & orientation (notweighted)
728
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
729
+ im_cell_n[edge:-edge,edge:-edge],
730
+ orientation_dev, cmap_angle="coolwarm",
731
+ path_png= os.path.join(figures,"Orientation_overlay.png"),
732
+ label="Orientation",dpi=dpi,
733
+ # ,cmap_cell="Greys_r",cmap_fiber="Greys_r", ### use default values here
734
+ # cmap_angle="viridis", alpha_ori =0.8, alpha_cell = 0.4, alpha_fiber = 0.4,
735
+ omin=-1, omax=1,scale=scale)
736
+
737
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
738
+ im_cell_n[edge:-edge,edge:-edge],
739
+ ori, cmap_angle="turbo",
740
+ path_png= os.path.join(figures,"Coherency_overlay.png"),
741
+ label="Coherency",dpi=dpi,
742
+ # ,cmap_cell="Greys_r",cmap_fiber="Greys_r", ### use default values here
743
+ # cmap_angle="viridis", alpha_ori =0.8, alpha_cell = 0.4, alpha_fiber = 0.4,
744
+ omin=0, omax=1,scale=scale)
745
+
746
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
747
+ im_cell_n[edge:-edge,edge:-edge],
748
+ angle_dev, cmap_angle="viridis_r",
749
+ path_png= os.path.join(figures,"Angle_Deviation_overlay.png"),
750
+ label="Angle Deviation",dpi=dpi,
751
+ # ,cmap_cell="Greys_r",cmap_fiber="Greys_r", ### use default values here
752
+ # cmap_angle="viridis", alpha_ori =0.8, alpha_cell = 0.4, alpha_fiber = 0.4,
753
+ omin=0, omax=90,scale=scale)
754
+
755
+ plot_fancy_overlay(im_fiber_n[edge:-edge,edge:-edge],
756
+ im_cell_n[edge:-edge,edge:-edge],
757
+ angle_no_reference, cmap_angle="gist_rainbow",
758
+ path_png= os.path.join(figures,"Angle_NoReference_overlay.png"),
759
+ label="Angle (x-axis)",dpi=dpi,
760
+ # ,cmap_cell="Greys_r",cmap_fiber="Greys_r", ### use default values here
761
+ # cmap_angle="viridis", alpha_ori =0.8, alpha_cell = 0.4, alpha_fiber = 0.4,
762
+ omin=-90, omax=90,
763
+ scale=scale)
764
+
765
+
648
766
  plt.close("all")
649
- # Polar plots
650
- plot_polar(results_angle['Angles Plotting'], results_angle['Coherency (weighted by intensity)'],
651
- path_png= os.path.join(figures,"polar_coherency_weighted.png"), label = "Coherency (weighted)",dpi=dpi)
652
767
 
653
-
768
+ # Polar plots
654
769
  plot_polar(results_angle['Angles Plotting'], results_angle['Coherency (weighted by intensity)'],
655
770
  path_png= os.path.join(figures,"polar_coherency_double.png"), label = "Coherency (weighted)",
656
- something2 = results_angle['Coherency'], label2 = "Coherency",dpi=dpi)
657
-
658
- plot_polar(results_angle['Angles Plotting'], results_angle['Mean Intensity'],
659
- path_png= os.path.join(figures,"polar_intensity.png"), label = "Mean Intensity",dpi=dpi)
771
+ something2 = results_angle['Coherency'], label2 = "Coherency",dpi=dpi, vmin=0,vmax=1)
660
772
 
661
773
  plot_polar(results_angle['Angles Plotting'], results_angle['Orientation (weighted by intensity and coherency)'],
662
- path_png= os.path.join(figures,"Orientation_weighted_polar.png"), label = "Orientation",dpi=dpi)
774
+ path_png= os.path.join(figures,"polar_orientation_double.png"), label = "Orientation (weighted)",
775
+ something2 = results_angle['Orientation'], label2 = "Orientation",dpi=dpi, vmin=-1,vmax=1)
663
776
 
664
- plot_polar(results_angle['Angles Plotting'], results_angle['Orientation'],
665
- path_png= os.path.join(figures,"Orientation_polar.png"), label = "Orientation",dpi=dpi)
666
- plt.close("all")
667
777
  # summarizing triple plot
668
778
  plot_triple(results_angle,results_total , path_png= os.path.join(figures,"Triple_plot.png") ,dpi=dpi)
669
-
670
- # quiver plots with center overlay
671
- quiv_coherency_center(vec0=min_evec[:,:,0] ,vec1=min_evec[:,:,1] ,coherency_map=ori,
672
- center0=center_small[0],center1 = center_small[1],
673
- path_png= os.path.join(figures,"quiv_coherency_center.png"),dpi=dpi )
674
- plt.close("all")
675
- # image fiber + segmention
676
- plot_fiber_seg(fiber_image=normalize(im_fiber_n[edge:-edge,edge:-edge]) ,
677
- c0=center_small[0],c1=center_small[1],
678
- segmention=segmention["mask"][edge:-edge,edge:-edge],
679
- path_png=os.path.join(figures,"fiber_segemention.png"),dpi=dpi,scale=scale )
680
-
681
- # plot overlaywith fiber image
682
- plot_overlay(fiber_image=normalize(im_fiber_n[edge:-edge,edge:-edge]) ,
683
- c0=center_small[0],c1=center_small[1], vec0=min_evec[:,:,0],
684
- vec1=min_evec[:,:,1], coherency_map=ori, show_n=15,
685
- segmention=segmention["mask"][edge:-edge,edge:-edge],
686
- path_png=os.path.join(figures,"overlay.png"),dpi=dpi ,scale=scale)
687
-
688
- plot_overlay(fiber_image=normalize(im_fiber_n[edge:-edge,edge:-edge]) ,
689
- c0=center_small[0],c1=center_small[1], vec0=min_evec[:,:,0],
690
- vec1=min_evec[:,:,1], coherency_map=ori,show_n=10,
691
- segmention=segmention["mask"][edge:-edge,edge:-edge],
692
- path_png=os.path.join(figures,"overlay2.png"),dpi=dpi ,scale=scale)
779
+
780
+ if cell_list is not None:
781
+
782
+ # image fiber + segmention
783
+ plot_fiber_seg(fiber_image=normalize(im_fiber_n[edge:-edge,edge:-edge]) ,
784
+ c0=center_small[0],c1=center_small[1],
785
+ segmention=segmention["mask"][edge:-edge,edge:-edge],
786
+ path_png=os.path.join(figures,"fiber_celloutline.png"),dpi=dpi,scale=scale )
787
+ # plot overlaywith fiber image
788
+ plot_overlay(fiber_image=normalize(im_fiber_n[edge:-edge,edge:-edge]) ,
789
+ c0=center_small[0],c1=center_small[1], vec0=min_evec[:,:,0],
790
+ vec1=min_evec[:,:,1], coherency_map=ori, show_n=15,
791
+ segmention=segmention["mask"][edge:-edge,edge:-edge],
792
+ path_png=os.path.join(figures,"fiber_cell_structure.png"),dpi=dpi ,scale=scale)
793
+ else:
794
+ # plot overlaywith fiber image
795
+ plot_overlay(fiber_image=normalize(im_fiber_n[edge:-edge,edge:-edge]) ,
796
+ c0=center_small[0],c1=center_small[1], vec0=min_evec[:,:,0],
797
+ vec1=min_evec[:,:,1], coherency_map=ori, show_n=15,
798
+ segmention=None,
799
+ path_png=os.path.join(figures,"fiber_structure.png"),dpi=dpi ,scale=scale)
800
+
801
+
693
802
  plt.close("all")
694
803
  ### DISTANCE PLOTS
695
804
  # plot shells - deactived as it consumes a lot of time
@@ -701,13 +810,34 @@ def StuctureAnalysisMain(fiber_list,
701
810
 
702
811
  plot_distance(results_distance,string_plot = "Intensity Norm (individual)",
703
812
  path_png=os.path.join(figures,"Intensity_distance.png"),dpi=dpi)
704
- plt.close("all")
813
+
814
+
705
815
  # save raw cell image
706
816
  plot_cell(im_cell_n, path_png=os.path.join(figures,"cell-raw.png"), scale=scale, dpi=dpi)
817
+ plot_cell(normalize(im_fiber_n[edge:-edge,edge:-edge]), path_png=os.path.join(figures,"fiber-raw.png"), scale=scale, dpi=dpi)
707
818
 
708
- plt.close("all")
819
+ plt.close("all")
820
+
821
+ if mode_saenopy == True: # only evaluates a single item at each call and returns the arrays
822
+ return angle_no_reference, orientation_dev, ori, min_evec, excel_total, excel_angles, excel_distance
823
+
824
+ # np.save(os.path.join(numpy_out, "segmention.npy" ),segmention["mask"][edge:-edge,edge:-edge])
825
+ # np.save(os.path.join(numpy_out, "AngleDeviationMap.npy" ),angle_dev )
826
+ # #np.save(os.path.join(numpy_out, "AngleMap(weight_int).npy" ),angle_dev_weighted)
827
+ # np.save(os.path.join(numpy_out, "AngleDeviationMap(weight_int_coh).npy"),angle_dev_weighted2 )
828
+ # np.save(os.path.join(numpy_out, "AngleMap_NoReference.npy"), angle_no_reference )
829
+ # np.save(os.path.join(numpy_out, "OrientationMap.npy" ),orientation_dev )
830
+ # #np.save(os.path.join(numpy_out, "OrientationMap_weight_int.npy" ),orientation_dev_weighted)
831
+ # np.save(os.path.join(numpy_out, "OrientationMap_weight_intcoh.npy" ),orientation_dev_weighted2 )
832
+ # np.save(os.path.join(numpy_out, "FiberImageCrop.npy" ),normalize(im_fiber_n[edge:-edge,edge:-edge]) )
833
+ # np.save(os.path.join(numpy_out, "CoherencyMap.npy" ),ori )
834
+ # #np.save(os.path.join(numpy_out, "CoherencyMap(weighted_int).npy" ),ori_weight2)
835
+ # np.save(os.path.join(numpy_out, "Vector_min_ax0.npy"),min_evec[:,:,0])
836
+ # np.save(os.path.join(numpy_out, "Vector_min_ax1.npy"),min_evec[:,:,1])
837
+ # np.save(os.path.join(numpy_out, "center.npy"),center_small)
838
+
839
+
709
840
 
710
-
711
841
  return
712
842
 
713
843
 
@@ -733,10 +863,10 @@ def SummarizeResultsTotal(data, output_folder= None):
733
863
  'Overall weighted Oriantation (std all cells)': []}
734
864
 
735
865
  for i, path in enumerate(list_total):
736
- results_total_combined['Orientation (weighted by coherency)'].append(float(pd.read_excel(list_total[i])['Orientation (weighted by coherency)']))
737
- results_total_combined['Orientation (weighted by intensity and coherency)'].append(float(pd.read_excel(list_total[i])['Orientation (weighted by intensity and coherency)']))
738
- results_total_combined['Mean Angle (weighted by coherency)'].append(float(pd.read_excel(list_total[i])['Mean Angle (weighted by coherency)']))
739
- results_total_combined['Mean Angle (weighted by intensity and coherency)'].append(float(pd.read_excel(list_total[i])['Mean Angle (weighted by intensity and coherency)']))
866
+ results_total_combined['Orientation (weighted by coherency)'].append(float(pd.read_excel(list_total[i])['Orientation (weighted by coherency)'][0]))
867
+ results_total_combined['Orientation (weighted by intensity and coherency)'].append(float(pd.read_excel(list_total[i])['Orientation (weighted by intensity and coherency)'][0]))
868
+ results_total_combined['Mean Angle (weighted by coherency)'].append(float(pd.read_excel(list_total[i])['Mean Angle (weighted by coherency)'][0]))
869
+ results_total_combined['Mean Angle (weighted by intensity and coherency)'].append(float(pd.read_excel(list_total[i])['Mean Angle (weighted by intensity and coherency)'][0]))
740
870
  results_total_combined['Path'].append(str(list_total[i]))
741
871
 
742
872
  ovreall_orientation = np.nanmean(results_total_combined['Orientation (weighted by intensity and coherency)'])