예제 #1
0
def change_composite_display(imp, luts):
  '''
  luts = [["green",0,1],["red",0,1]]
  '''
  # make Luts
  grayLut = LUT.createLutFromColor(Color.white)
  #grayLut.min = luts[0][1]; grayLut.max = luts[0][2]
  #print grayLut
  
  greenLut = LUT.createLutFromColor(Color.green)
  #greenLut.min = luts[1][1]; greenLut.max = luts[1][2]
  #print greenLut
  # change display mode (otherwise the Lut changes do not work)
  imp.setDisplayMode(IJ.COLOR)
  # set Luts
  print "imp.isComposite()",imp.isComposite()
  imp.setC(1); imp.setChannelLut(grayLut)
  imp.setDisplayRange(luts[0][1], luts[0][2])
  imp.setC(2); imp.setChannelLut(greenLut)
  #IJ.run(imp, "Fire", "");
  #IJ.setMinAndMax(imp, 100, 255);
  imp.setDisplayRange(luts[1][1], luts[1][2])
  #imp.getProcessor().invertLut()
  # check that it worked
  print imp.getLuts()
  imp.setDisplayMode(IJ.COMPOSITE)
  return imp
예제 #2
0
파일: display.py 프로젝트: toyo97/bcmeasure
def apply_lut(cs, cmap):
    # type: (CellStack, str) -> None
    """
Apply a different Look Up Table according to the given cmap name

    :param cmap: Can be 'fire'
    """
    stats = StackStatistics(cs)
    ll = LutLoader()
    if cmap == 'fire':
        cm = ll.open('luts/fire.lut')
        # print("Stats.max " + str(stats.max))
        lut = LUT(cm, stats.min, stats.max)
        cs.setLut(lut)
    else:
        IJ.error('Invalid color map: ' + cmap + '\nDefault LUT applied')
예제 #3
0
def analyze_homogeneity(image_title):
    IJ.selectWindow(image_title)
    raw_imp = IJ.getImage()
    IJ.run(raw_imp, "Duplicate...", "title=Homogeneity duplicate")
    IJ.selectWindow('Homogeneity')
    hg_imp = IJ.getImage()

    # Get a 2D image
    if hg_imp.getNSlices() > 1:
        IJ.run(hg_imp, "Z Project...", "projection=[Average Intensity]")
        hg_imp.close()
        IJ.selectWindow('MAX_Homogeneity')
        hg_imp = IJ.getImage()
        hg_imp.setTitle('Homogeneity')

    # Blur and BG correct the image
    IJ.run(hg_imp, 'Gaussian Blur...', 'sigma=' + str(HOMOGENEITY_RADIUS) + ' stack')

    # Detect the spots
    IJ.setAutoThreshold(hg_imp, HOMOGENEITY_THRESHOLD + " dark")
    rm = RoiManager(True)
    table = ResultsTable()
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                          ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,
                          Measurements.AREA, # measurements
                          table, # Output table
                          0, # MinSize
                          500, # MaxSize
                          0.0, # minCirc
                          1.0) # maxCirc
    pa.setHideOutputImage(True)
    pa.analyze(hg_imp)

    areas = table.getColumn(table.getHeadings().index('Area'))

    median_areas = compute_median(areas)
    st_dev_areas = compute_std_dev(areas, median_areas)
    thresholds_areas = (median_areas - (2 * st_dev_areas), median_areas + (2 * st_dev_areas))

    roi_measurements = {'integrated_density': [],
                        'max': [],
                        'area': []}
    IJ.setForegroundColor(0, 0, 0)
    for roi in rm.getRoisAsArray():
        hg_imp.setRoi(roi)
        if REMOVE_CROSS and hg_imp.getStatistics().AREA > thresholds_areas[1]:
            rm.runCommand('Fill')
        else:
            roi_measurements['integrated_density'].append(hg_imp.getStatistics().INTEGRATED_DENSITY)
            roi_measurements['max'].append(hg_imp.getStatistics().MIN_MAX)
            roi_measurements['integrated_densities'].append(hg_imp.getStatistics().AREA)

        rm.runCommand('Delete')

    measuremnts = {'mean_integrated_density': compute_mean(roi_measurements['integrated_density']),
                   'median_integrated_density': compute_median(roi_measurements['integrated_density']),
                   'std_dev_integrated_density': compute_std_dev(roi_measurements['integrated_density']),
                   'mean_max': compute_mean(roi_measurements['max']),
                   'median_max': compute_median(roi_measurements['max']),
                   'std_dev_max': compute_std_dev(roi_measurements['max']),
                   'mean_area': compute_mean(roi_measurements['max']),
                   'median_area': compute_median(roi_measurements['max']),
                   'std_dev_area': compute_std_dev(roi_measurements['max']),
                   }

    # generate homogeinity image
    # calculate interpoint distance in pixels
    nr_point_columns = int(sqrt(len(measuremnts['mean_max'])))
    # TODO: This is a rough estimation that does not take into account margins or rectangular FOVs
    inter_point_dist = hg_imp.getWidth() / nr_point_columns
    IJ.run(hg_imp, "Maximum...", "radius="+(inter_point_dist*1.22))
    # Normalize to 100
    IJ.run(hg_imp, "Divide...", "value=" + max(roi_measurements['max'] / 100))
    IJ.run(hg_imp, "Gaussian Blur...", "sigma=" + (inter_point_dist/2))
    hg_imp.getProcessor.setMinAndMax(0, 255)

    # Create a LUT based on a predefined threshold
    red = zeros(256, 'b')
    green = zeros(256, 'b')
    blue = zeros(256, 'b')
    acceptance_threshold = HOMOGENEITY_ACCEPTANCE_THRESHOLD * 256 / 100
    for i in range(256):
        red[i] = (i - acceptance_threshold)
        green[i] = (i)
    homogeneity_LUT = LUT(red, green, blue)
    hg_imp.setLut(homogeneity_LUT)

    return hg_imp, measuremnts
						IJ.run(mergedImage,"Refractive Signal Loss Correction",params)
						dataImage = WindowManager.getImage("App Corrected")
						mergedImage.close()
						refCorrectedImage = WindowManager.getImage("Ref Corrected")
						refCorrectedImage.close()
				else:
					dataImage = channelImages[analysisChannel-1]
					if (refChannel > 0):
						params = ("reference_channel=" + str(refChannel) + 
								" application_channel=" + str(analysisChannel) + " automatic_operation" +
								" generate_log max_slice=43 surface_slice=87")
						IJ.run(theImage,"Refractive Signal Loss Correction",params)
						dataImage = WindowManager.getImage("App Corrected")
						refCorrectedImage = WindowManager.getImage("Ref Corrected")
						refCorrectedImage.close()
				dataImage.setLut(LUT.createLutFromColor(Color.WHITE))
				#dataImage.setCalibration(calibration)
				dataImage.show()
				if (processFilter > 0):
					if processFilter == 1:
						IJ.run(dataImage,"Minimum...", "radius=2 stack")
					if processFilter == 2:
						IJ.run(dataImage,"Median...", "radius=2 stack")
				theImage.close()
					
				## Now runs the object counter on the processed tile
				params = ("volume surface nb_of_obj._voxels " + 
						"nb_of_surf._voxels integrated_density mean_gray_value " +
						"std_dev_gray_value median_gray_value minimum_gray_value " +
						"maximum_gray_value centroid mean_distance_to_surface " + 
						"std_dev_distance_to_surface median_distance_to_surface centre_of_mass " +
    Canceled = False

if not Canceled:

    for f in file_path:

        # Hyperstackの作成
        imp = IJ.openImage(f)
        nFrame = imp.getNSlices(
        ) / n_Channel  # 元画像のAttributionがなぜかFrame が Z sliceとなっている

        # File 保存のための文字列作成
        save_file = imp.getTitle().replace(".tif", "-stack.tif")
        save_path = os.path.join(save_dir, save_file)

        # Hyper Stackに変換
        h_imp = HyperStackConverter.toHyperStack(imp, n_Channel, 1, nFrame,
                                                 "Composite")

        del imp

        # Hyper Stack の Channelカラー変更
        for i, color in enumerate(user_color):
            h_imp.setC(i + 1)
            h_imp.setLut(LUT.createLutFromColor(Colors[color]))

        # ファイルを保存
        IJ.saveAsTiff(h_imp, save_path)
        # IJ.log(save_path)
        del h_imp
	active_image.setRoi(proi)
	return active_image

## Main body of script starts here
od = OpenDialog("Select parent LSM file...")
parentLSMFilePath = od.getPath()
if parentLSMFilePath is not None:
	tileConfigFilePath = parentLSMFilePath + "_tiles/resized/TileConfiguration.registered.txt"
	scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif")
	print scale_info
	coords = read_tileconfig_file(tileConfigFilePath)
	full_keys = ["tile_"+str(i) for i in range(1,len(coords.keys())+1)]
	coords_vals = normalize_coords_in_list(get_list_from_dict(full_keys,coords))
	im = IJ.getImage()
	if im.getNChannels() == 1:
		LUTarray = [LUT.createLutFromColor(Color.WHITE)]
	elif im.getNChannels() == 2:
		LUTarray = [LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.WHITE)]
	elif im.getNChannels() == 3:
		LUTarray = [LUT.createLutFromColor(Color.GREEN),LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.WHITE)]
	elif im.getNChannels() == 4:
		LUTarray = [LUT.createLutFromColor(Color.BLUE),LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.GREEN),LUT.createLutFromColor(Color.WHITE)]
	elif im.getNChannels() == 5:
		LUTarray = [LUT.createLutFromColor(Color.BLUE),LUT.createLutFromColor(Color.RED),LUT.createLutFromColor(Color.GREEN),LUT.createLutFromColor(Color.YELLOW),LUT.createLutFromColor(Color.WHITE)]
	else:
		LUTarray = []

	nbgd = NonBlockingGenericDialog("Pick freehand ROI")
	nbgd.setLocation(0,0)
	nbgd.addMessage("OK to run, cancel to exit")
	nbgd.showDialog()
예제 #7
0
  
# adjust min and max, since we know them
imp.getProcessor().setMinAndMax(0, w-1)
imp.show()

# Create a random 8-bit image the hard way...
width = 512
height = 512
  
pix = zeros(width * height, 'b')
Random().nextBytes(pix)

channel = zeros(256, 'b')
for i in range(256):
    channel[i] = (i -128) 
cm = LUT(channel, channel, channel)
imp_rand_hard = ImagePlus("Random", ByteProcessor(width, height, pix, cm))
imp_rand_hard.show()

# random 16 bit the hard way...
imp = IJ.createImage("An Easy Random Image 8 bit image", "8-bit", 512, 512, 1)
Random().nextBytes(imp.getProcessor().getPixels())
imp.show()

print(sys.getsizeof(int))
print(sys.getsizeof(bytes))

# 1 - Obtain an image
blobs = IJ.openImage("http://imagej.net/images/blobs.gif")
blobs.setTitle("blobs")
blobs.show()
if dirPath is not None:
	dc2 = DirectoryChooser("Select output directory...")
	outPath = dc2.getDirectory()
	if outPath is not None:
		gd = GenericDialog("Options...")
		gd.addCheckbox("Recolor_images",True)
		gd.showDialog()
		if (gd.wasOKed()):
			doRecolor = gd.getNextBoolean()
		
			for f in os.listdir(dirPath):
				if f.endswith(".tif") or f.endswith(".tiff"):
					theImage = IJ.openImage(dirPath+f)
					IJ.log("Loaded " + f)
					palette = [Color.GREEN,Color.RED,Color.BLUE]
					if (theImage.getNChannels() < 4):
						if doRecolor:
							for i in range(theImage.getNChannels()):
								theImage.setChannelLut(LUT.createLutFromColor(palette[i]),i+1)
						try:
							sc = StackConverter(theImage)
							sc.convertToRGB()
							IJ.saveAsTiff(theImage,outPath+os.path.splitext(f)[0]+"_rgb.tif")
							IJ.log("Completed " + f)
						except:
							IJ.log("Exception thrown during RGB conversion, image skipped")
						finally:
							theImage.close()
					else:
						IJ.log("Image has too many color channels")