Exemplo n.º 1
0
    def doInBackground(self):
        imp = self.imp
        print "started"

        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
        print st

        # Disable frame3 buttons in GUI while loading ROIs
        f2_btn_original.setEnabled( 0 )
        f2_btn_label.setEnabled( 0 )
        f2_btn_prev.setEnabled( 0 )
        f2_btn_next.setEnabled( 0 )


        RM = RoiManager()        # we create an instance of the RoiManager class
        rm = RM.getRoiManager()  # "activate" the RoiManager otherwise it can behave strangely
        rm.reset()
        rm.runCommand(imp,"Show All without labels") # we make sure we see the ROIs as they are loading


        imp2 = imp.duplicate()
        ip = imp2.getProcessor()
        width = imp2.getWidth()
        height = imp2.getHeight() - 1

        max_label = int(imp2.getStatistics().max)
        max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros)
        IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed

        for j in range(height):
           for i in range(width):
              current_pixel_value = ip.getValue(i,j)
              if current_pixel_value > 0:
                 IJ.doWand(imp2, i, j, 0.0, "Legacy smooth");

                 # We add this ROI to the ROI manager
                 roi = imp2.getRoi()
                 roi.setName(str(int(current_pixel_value)).zfill(max_digits))
                 rm.addRoi(roi)

                 ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", ....

                 # Update ProgressBar
                 progress = int((current_pixel_value / max_label) * 100)
                 self.super__setProgress(progress)

        rm.runCommand(imp,"Sort") # Sort the ROIs in the ROI manager
        rm.runCommand(imp,"Show All without labels")

        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
        print st

        print "Finished"
Exemplo n.º 2
0
    def doInBackground(self):
       try:                # In case there is an error, so that FIJI doesn't crash
          print "INICIO"
          print self.files
          print self.pix_erosion_mult

          label_files = [f for f in self.files if f.endswith('_label.png') or
                                                  f.endswith('_label.tif') or
                                                  f.endswith('_label.jpg')]
          total_label_files = len(label_files)

          print "total label files:"
          print total_label_files
          gvars["total label files"] = total_label_files



          for filenum, f in enumerate(label_files): # Loop through the files in the directory
            self.label_update(filenum+1, total_label_files)
            label_file = f
            print "----"
            print label_file
            original_name = re.sub(r"_label.*", "",f) # get name of the original image without extension

            if (original_name+".tif") in self.files: # for an original image with extension .tif
               original_file = original_name+".tif"
               print original_file
            elif (original_name+".tiff") in self.files: # for an original image with extension .tiff (with double f)
               original_file = original_name+".tiff"
               print original_file
            else:                   # If there is no original image
               original_file = "None"
               print original_file

            path_multiple = gvars['path_multiple_image_directory']
            print path_multiple

            ########### Section Label To Roi ###########
            RM = RoiManager()
            rm = RM.getRoiManager()
            label_image = IJ.openImage(path_multiple + "\\" + label_file)

            rm.reset()
            rm.runCommand(label_image,"Show All without labels") # we make sure we see the ROIs as they are loading

            imp2 = label_image.duplicate()
            ip = imp2.getProcessor()
            width = imp2.getWidth()
            height = imp2.getHeight() - 1

            max_label = int(imp2.getStatistics().max)
            max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros)
            IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed

            for j in range(height):
               for i in range(width):
                  current_pixel_value = ip.getValue(i,j)
                  if current_pixel_value > 0:
                     IJ.doWand(imp2, i, j, 0.0, "Legacy smooth");

                     # We add this ROI to the ROI manager
                     roi = imp2.getRoi()
                     roi.setName(str(int(current_pixel_value)).zfill(max_digits))
                     rm.addRoi(roi)

                     ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", ....

                     # Update ProgressBar
                     progress = int((current_pixel_value / max_label) * 100)
                     self.super__setProgress(progress)

            rm.runCommand(label_image,"Sort") # Sort the ROIs in the ROI manager
            rm.runCommand(label_image,"Show All without labels")

            ######### Section ROI erotion #########

            for i in range(0, rm.getCount()):
               roi = rm.getRoi(i)
               new_roi = RoiEnlarger.enlarge(roi, -self.pix_erosion_mult) # Important to use this instead of the IJ.run("Enlarge... much faster!!
               rm.setRoi(new_roi,i)

            ####### Section Save ROIs ##############
            print original_name
            path_to_multiple_ROIs = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "RoiSet.zip"
            print path_to_multiple_ROIs
            rm.runCommand("Save", path_to_multiple_ROIs)
            print("ROIs saved")

            ####### Section open Original Image ##############
            if original_file != "None": # If there is an original image file besides the label image, we'll measure and generate table of measurements
                print "There is an original image associated to this label"
                original_image = IJ.openImage(path_multiple + "\\" + original_file)
                IJ.run(original_image, "Enhance Contrast", "saturated=0.35")
                rm.runCommand(original_image,"Show All without labels")
                #original_image.show()

                table_message = []
                is_scaled = original_image.getCalibration().scaled()
                if is_scaled:
                    spatial_cal = "True"
                else:
                    spatial_cal = "False"

                nChannels = original_image.getNChannels()

                print "Total channels:"
                print nChannels
                for current_channel in range(1,nChannels+1):
                   print "Current channel:"
                   print current_channel

                   original_image.setSlice(current_channel)
                   current_slice = str(original_image.getCurrentSlice()) #Get current slice for saving into filename
                   print "Current slice:"
                   print current_slice

                   IJ.run("Clear Results", "")
                   rm.runCommand(original_image,"Select All");
                   rm.runCommand(original_image,"Measure")

                   table = ResultsTable.getResultsTable().clone()
                   IJ.selectWindow("Results")
                   IJ.run("Close")


                   for i in range(0, table.size()):
                      table.setValue('File', i, str(original_name))
                      table.setValue('Channel', i, current_channel)
                      table.setValue('Pixels_eroded', i, str(self.pix_erosion_mult))
                      table.setValue('Spatial_calibration', i, spatial_cal)

                   table.show("Tabla actualizada")

                   path_to_multiple_Tables = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_Channel_" + str(current_channel) + ".csv"

                   IJ.saveAs("Results", path_to_multiple_Tables)

                   # Section Save jpg with outlines
                   path_to_multiple_outline = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "Outlines.jpg"
                   outlines_image = original_image.flatten()
                   IJ.saveAs(outlines_image, "JPG", path_to_multiple_outline)

                   IJ.run("Close")


            else:
                print "There is NOT an original image associated to this label"


            label_image.close()

         ####### Section ending ##############

       except Exception as e:
          print e