From 8611f68b7c64085a07811f16d9e0c7aae8fc2c57 Mon Sep 17 00:00:00 2001 From: Valentin Valls <valentin.valls@esrf.fr> Date: Tue, 8 Oct 2024 10:36:50 +0200 Subject: [PATCH] Remove blank lines --- SampleAlignment/SampleAlignment.py | 198 ++++++++++++++--------------- SampleAlignment/TomoSampleAlign.py | 62 ++++----- SamplesDS/TomoSample.py | 14 +- 3 files changed, 137 insertions(+), 137 deletions(-) diff --git a/SampleAlignment/SampleAlignment.py b/SampleAlignment/SampleAlignment.py index beb90f5..323d9ea 100644 --- a/SampleAlignment/SampleAlignment.py +++ b/SampleAlignment/SampleAlignment.py @@ -19,13 +19,13 @@ import math class OffsetsCalculation: - + def __init__(self,resolution,imageDir,stand,borderType): - + #monkey.patch_all(thread=False) self.totalProcessingTime = 0 - + #self.sampleSizeX = sampleSize[0] #self.sampleSizeY = sampleSize[1] #self.sampleSizeZ = sampleSize[2] @@ -36,34 +36,34 @@ class OffsetsCalculation: self.pathImg = '/users/muzelle/Desktop/success2/007_HA-300_6.5_NUS2__004_/007_HA-300_6.5_NUS2__004_0000.edf' self.pathFlat = '/users/muzelle/Desktop/success2/007_HA-300_6.5_NUS2__004_/refHST0000.edf' self.pathDark = '/users/muzelle/Desktop/success2/007_HA-300_6.5_NUS2__004_/dark.edf' - + self.resolution = resolution - + self.stand = stand - + self.borderType = borderType - + self.img = None self.flat = None self.dark = None - + self.dispImg = None self.intImg = None - + self.centImgY = None self.centImgX = None - + self.centerY = None self.centerX = None - + self.leftBorder = None self.rightBorder = None - + self.borderDetected = "false" - + def imagesOpening(self): - + start = time.time() self.img = fabio.open(self.pathImg) @@ -72,43 +72,43 @@ class OffsetsCalculation: self.centImgY = int(self.img.data.shape[0]/2) self.centImgX = int(self.img.data.shape[1]/2) - + imagesOpeningTime = time.time()-start self.totalProcessingTime += imagesOpeningTime print("Time to open images: "+str(imagesOpeningTime)) - - + + def imageContrastEnhancement(self): - + start = time.time() - + filtImg = np.subtract(self.img.data,self.dark.data).astype(np.float32) filtImgFlat = np.subtract(self.flat.data,self.dark.data).astype(np.float32) corrImg = np.divide(filtImg,filtImgFlat).astype(np.float32) corrImg[corrImg < 0] = 0 - + enhImg = cv2.normalize(corrImg, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) - + self.img = corrImg - + imageContrastEnhancementTime = time.time()-start self.totalProcessingTime += imageContrastEnhancementTime print("Time to enhance image contrast: "+str(imageContrastEnhancementTime)) - + def imageFiltering(self): - + start = time.time() blurImg = cv2.bilateralFilter(self.img,9,75,75) blurImg = cv2.normalize(blurImg, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) - + self.img = blurImg self.dispImg = blurImg - + imageFilteringTime = time.time()-start self.totalProcessingTime += imageFilteringTime print("Time to filter image: "+str(imageFilteringTime)) - + def edgesDetection(self): start = time.time() @@ -122,13 +122,13 @@ class OffsetsCalculation: thr = np.median(edges)*1.33 edges = np.uint8(edges < -thr) - + #measures = cv2.connectedComponentsWithStats(edges, 8, cv2.CV_32S) - + #labImg = measures[1] - + #areas = measures[2][:,cv2.CC_STAT_AREA] - + labImg = measure.label(edges, neighbors=8, background=0) labImg += 1 @@ -142,149 +142,149 @@ class OffsetsCalculation: labImg = morphology.remove_small_objects(labImg,noise,in_place=True) edges = np.uint8(labImg > 0) - + #self.dispImg[edges > 0] = 0 - + #savedImg = fabio.edfimage.EdfImage() #savedImg.data = self.dispImg #savedImg.write('/segfs/tango/tmp/clemence/SampleAlignment/edgesDetected.edf') - + self.img = labImg - + edgesDetectionTime = time.time()-start self.totalProcessingTime += edgesDetectionTime print("Time to find edges: "+str(edgesDetectionTime)) - - + + def sampleCenterXCalculation(self): - + start = time.time() - + props = measure.regionprops(self.img,self.dispImg) - + centroids = [(p.centroid[0],p.centroid[1]) for p in props if p.max_intensity > 200] - + if len(centroids) != 0: self.borderDetected = "true" - + if self.stand == 'absent': - - + + if self.borderType == 'straight': - + self.leftBorder = np.min(centroids,axis=0)[1] self.rightBorder = np.max(centroids,axis=0)[1] - + self.centerX = int((self.rightBorder - self.leftBorder)/2+self.leftBorder) - + if self.borderType == 'irregular': - + edges = self.img > 0 - + self.leftBorder = np.min(centroids,axis=0)[1] - + print('left border: '+str(self.leftBorder)) - + self.rightBorder = np.max(centroids,axis=0)[1] - + print('right border: '+str(self.rightBorder)) - + self.centerX = int(np.mean([(np.min(np.where(edges[raw,:])[0])+np.max(np.where(edges[raw,:])[0]))/2 for raw in range(edges.shape[0]) if len(np.where(edges[raw,:])[0]) != 0 and (np.max(np.where(edges[raw,:])[0])-np.min(np.where(edges[raw,:])[0])) > 200] )) - + if self.borderType == 'oblique': - + edges = self.img > 0 - + areas = [p.area for p in props] - + fullBorder = [p.label for p in props if p.area == np.max(areas)][0] - + centerRawByRaw = np.array([((np.min(np.where(edges[raw,:])[0])+np.max(np.where(edges[raw,:])[0]))/2,raw) for raw in range(edges.shape[0]) if len(np.where(edges[raw,:])[0]) != 0 and (np.max(np.where(edges[raw,:])[0])-np.min(np.where(edges[raw,:])[0])) > 100]) - + meanCenter = np.median(centerRawByRaw,axis=0) - + rows = np.where(self.img == fullBorder)[0] cols = np.where(self.img == fullBorder)[1] - + ya = np.mean(rows[np.where(cols == np.min(cols))]) yb = np.mean(rows[np.where(cols == np.max(cols))]) xb = np.max(cols) xa = np.min(cols) - + slope = (yb-ya)/(xb-xa) - + self.centerX = (self.centImgY-meanCenter[1])/slope + meanCenter[0] - + offsetSX = (self.centImgX-self.centerX)*self.resolution*10**-3 - - + + centerXCalculationTime = time.time()-start self.totalProcessingTime += centerXCalculationTime - + print("Time to calculate sample center X: "+str(centerXCalculationTime)) - + return offsetSX - - + + def sampleCenterYCalculation(self): pass - + def localTomoCenterXCalculation(self): - + start = time.time() - + props = measure.regionprops(self.img,self.intImg) - + areas = [p.area for p in props] - + border = [p.centroid for p in props if p.area == np.max(areas) and p.max_intensity > 200] - + if len(border) == 0: - + offsetSX = self.img.shape[1] - + else: - + ret,binImg = cv2.threshold(self.dispImg,0,1,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) - + labImg = measure.label(binImg, neighbors=8, background=0) labImg += 1 props = measure.regionprops(labImg) - + areas = [p.area for p in props] - + sample = [p.centroid for p in props if p.area == np.max(areas)][0] - + if sample[1] > border[0][1]: - + self.borderDetected = "right" - + else: self.borderDetected = "left" - + self.centerX = border[0][1] - + offsetSX = (self.centImgX-self.centerX)*self.resolution*10**-3 - + centerXCalculationTime = time.time()-start self.totalProcessingTime += centerXCalculationTime - + print("Time to calculate sample center X: "+str(centerXCalculationTime)) - + return offsetSX def displayResults(self): - + try: self.centerX except NameError: @@ -293,26 +293,26 @@ class OffsetsCalculation: self.centerY except NameError: self.centerY = 0 - + print('\n') print('total processing time: '+str(self.totalProcessingTime)) print('\n') print('Sample center detected: '+str(self.centerX)+' in X and: '+str(self.centerY)+' in Y') print('Image center: '+str(self.centImgX)+' in X and: '+str(self.centImgY)+' in Y') - + def displayImage(self): - + edgesDetection = fabio.open('/segfs/tango/tmp/clemence/SampleAlignment/edgesDetected.edf') - + qapp = qt.QApplication([]) plot = Plot2D() plot.addImage(edgesDetection.data, legend='image') plot.show() qapp.exec_() - + if __name__ == '__main__': - + test = OffsetsCalculation(12.57,"/segfs/tango/tmp/clemence/SampleAlignment/","absent","straight") test.imagesOpening() test.imageContrastEnhancement() @@ -323,5 +323,5 @@ if __name__ == '__main__': #test.displayResults() #inst = OffsetsCalculation(0,"","","") #inst.displayImage() - - + + diff --git a/SampleAlignment/TomoSampleAlign.py b/SampleAlignment/TomoSampleAlign.py index c6ef7bd..86cec66 100644 --- a/SampleAlignment/TomoSampleAlign.py +++ b/SampleAlignment/TomoSampleAlign.py @@ -43,35 +43,35 @@ class TomoSampleAlign(Device): """ __metaclass__ = DeviceMeta # PROTECTED REGION ID(TomoSampleAlign.class_variable) ENABLED START # - + green_mode = PyTango.GreenMode.Gevent - + # # Blocking operation to find sample center # def alignment_task(self): try: self.info_stream("started alignment") - + self.is_error = False self.is_moving = True - + # alignment code print ("Alignment start\n") - + #gevent.sleep(3) - + align = OffsetsCalculation(self.attr_Resolution_read,self.attr_ImageDirectory_read,self.attr_StandDetection_read,self.attr_BorderType_read) align.imagesOpening() align.imageContrastEnhancement() align.imageFiltering() align.edgesDetection() - + if self.attr_AlignX_read: if self.attr_LocalTomo_read == True: offsetSX = align.localTomoCenterXCalculation() self.attr_BorderDetected_read = align.borderDetected - + print(self.attr_BorderDetected_read) else: offsetSX = align.sampleCenterXCalculation() @@ -81,22 +81,22 @@ class TomoSampleAlign(Device): offsetSY = align.sampleCenterYCalculation() else: offsetSY = 0 - + align.displayResults() - - + + print('Offset detected: '+str(int(offsetSX/(self.attr_Resolution_read*10**-3)))+' in X and: '+str(int(offsetSY/(self.attr_Resolution_read*10**-3)))+' in Y') print('Relative SY moving of '+str(offsetSX)) print('Relative SZ moving of '+str(offsetSY)) - + self.attr_AlignmentOffsets_read = [offsetSX,offsetSY] - + self.is_moving = False - + self.info_stream("\nfinished alignment") - - - + + + # catch all exceptions, print the traceback to the console and # add the information to the device status until acknowledgement except: @@ -106,10 +106,10 @@ class TomoSampleAlign(Device): except PyTango.DevFailed as ex: self.task_error = ex PyTango.Except.print_exception(ex) - + self.is_error = True self.is_moving = False - + # PROTECTED REGION END # // TomoSampleAlign.class_variable # ---------- @@ -183,13 +183,13 @@ class TomoSampleAlign(Device): Device.init_device(self) # PROTECTED REGION ID(TomoSampleAlign.init_device) ENABLED START # # init flags for state and status - + self.is_moving = False self.is_error = False - + self.running_task = None self.task_error = None - + self.attr_SampleSizeZ_read = 0.0 self.attr_SampleSizeY_read = 0.0 self.attr_SampleSizeX_read = 0.0 @@ -201,7 +201,7 @@ class TomoSampleAlign(Device): self.attr_AlignY_read = False self.attr_AlignmentOffsets_read = [0.0,0.0] print("done!") - + # PROTECTED REGION END # // TomoSampleAlign.init_device def always_executed_hook(self): @@ -416,7 +416,7 @@ class TomoSampleAlign(Device): _state = PyTango.DevState.MOVING else: _state = PyTango.DevState.ON - + self.set_state(_state) return _state # PROTECTED REGION END # // TomoSampleAlign.State @@ -425,7 +425,7 @@ class TomoSampleAlign(Device): def dev_status(self): # PROTECTED REGION ID(TomoSampleAlign.Status) ENABLED START # state = self.dev_state() - + self._status = "The device state is " if state == PyTango.DevState.FAULT: self._status += "FAULT" @@ -444,7 +444,7 @@ class TomoSampleAlign(Device): self._status += "MOVING" else: self._status += "ON" - + self.set_status(self._status) return self._status # PROTECTED REGION END # // TomoSampleAlign.Status @@ -454,12 +454,12 @@ class TomoSampleAlign(Device): @DebugIt() def AlignSample(self): # PROTECTED REGION ID(TomoSampleAlign.AlignSample) ENABLED START # - + self.running_task = gevent.spawn(self.alignment_task) print("Running started") self.is_moving = True - - + + # PROTECTED REGION END # // TomoSampleAlign.AlignSample def is_AlignSample_allowed(self): @@ -474,10 +474,10 @@ class TomoSampleAlign(Device): def main(args=None, **kwargs): # PROTECTED REGION ID(TomoSampleAlign.main) ENABLED START # - + # Enable gevents for the server kwargs.setdefault("green_mode", PyTango.GreenMode.Gevent) - + return run((TomoSampleAlign,), args=args, **kwargs) # PROTECTED REGION END # // TomoSampleAlign.main diff --git a/SamplesDS/TomoSample.py b/SamplesDS/TomoSample.py index 605eec0..c149c1d 100644 --- a/SamplesDS/TomoSample.py +++ b/SamplesDS/TomoSample.py @@ -110,7 +110,7 @@ class TomoSample(Device): def init_device(self): Device.init_device(self) # PROTECTED REGION ID(TomoSample.init_device) ENABLED START # - + self.attr_Name_read = "None" self.attr_Position_read = "None" self.attr_SizeX_read = 0.0 @@ -120,13 +120,13 @@ class TomoSample(Device): self.attr_AlignSY_read = 0.0 self.attr_AlignSZ_read = 0.0 self.attr_Aligned_read = False - + # # Get sample changer position from the device name dev_name = self.get_name() dom, fam, member = dev_name.split("/") self.attr_Position_read = member - + # PROTECTED REGION END # // TomoSample.init_device def always_executed_hook(self): @@ -236,12 +236,12 @@ class TomoSample(Device): @DebugIt() def dev_state(self): # PROTECTED REGION ID(TomoSample.State) ENABLED START # - + if self.attr_Name_read == "None": _state = PyTango.DevState.DISABLE else: _state = PyTango.DevState.ON - + self.set_state(_state) return _state # PROTECTED REGION END # // TomoSample.State @@ -251,7 +251,7 @@ class TomoSample(Device): @DebugIt() def Reset(self): # PROTECTED REGION ID(TomoSample.Reset) ENABLED START # - + myself = PyTango.DeviceProxy (self.get_name()) myself.write_attribute_asynch("Name" , "None") myself.write_attribute_asynch("SizeX" , 0) @@ -261,7 +261,7 @@ class TomoSample(Device): myself.write_attribute_asynch("AlignSY" , 0) myself.write_attribute_asynch("AlignSZ" , 0) myself.write_attribute_asynch("Aligned" , False) - + # PROTECTED REGION END # // TomoSample.Reset # ---------- -- GitLab