def rescaleimp(file_inpath,file_outpath): imp = IJ.openImage(file_inpath) img = ImgLib.wrap(imp) img2 = Resample(img,0.25) imp = ImgLib.wrap(img2) output = "nrrd=["+file_outpath+"]" IJ.run(imp, "Nrrd ... ", output)
def rescaleimp(file_inpath, file_outpath): """Function to rescale a single 3D NRRD image """ imp = IJ.openImage(file_inpath) img = ImgLib.wrap(imp) img2 = Resample(img, 0.25) imp = ImgLib.wrap(img2) output = "nrrd=[" + file_outpath + "]" IJ.run(imp, "Nrrd ... ", output)
def rescale(folder_in,folder_out): for filename in os.listdir(folder_in): imp =IJ.openImage(os.path.join(folder_in,filename)) img = ImgLib.wrap(imp) img2 = Resample(img,0.25) imp=ImgLib.wrap(img2) output = "nrrd=["+folder_out+filename+"]" IJ.run(imp, "Nrrd ... ", output) IJ.run("Collect Garbage", "");
def analyze_cells(imp, size, i, zmin): test = [] cdf = [] #ip = imp.getProcessor() #print "grabbing image..." #test = ip.getHistogram() #test = StackStatistics(imp).getHistogram() #print "calculating stack statistics..." #total = sum(test) #print "calculate threshold" #cdf = map(lambda x: x/float(total), acc(test)) #thresh = min(filter(lambda x: cdf[x] >= quantile, xrange(1,len(cdf)) )) max_int = StackStatistics(imp).max cal= imp.getCalibration() scale2D = cal.pixelWidth / cal.pixelDepth sigma = (size / cal.pixelWidth) * scale2D iso = Compute.inFloats(Scale2D(ImgLib.wrap(imp),scale2D)) peaks = DoGPeaks(iso, sigma, sigma * 0.5, thresh, 1) print "FOund", len(peaks), "peaks" ps = [] file = open(folder+str(i).zfill(4)+'_test_out.csv','w') exporter = csv.writer(file) for peak in peaks: if peak[2]>=zmin: print "raw",peak p = Point3f(peak) p.scale(cal.pixelWidth * 1/scale2D) print "sf", cal.pixelWidth * 1/scale2D print "scaled", p ps.append(p) t = () exporter.writerow([p.x, p.y, p.z]) file.close() if vis: iso = Compute.inFloats(Scale2D(Red(ImgLib.wrap(imp)),scale2D)) univ = Image3DUniverse(512,512) univ.addIcospheres(ps,Color3f(1,0,0), 2, size/2, "Cells").setLocked(True) univ.addOrthoslice(imp).setLocked(True) univ.show()
def rescale(folder_in, folder_out): """Function to rescale 3D NRRD image series""" for filename in os.listdir(folder_in): imp = IJ.openImage(os.path.join(folder_in, filename)) img = ImgLib.wrap(imp) img2 = Resample(img, 0.25) imp = ImgLib.wrap(img2) output = "nrrd=[" + folder_out + filename + "]" IJ.run(imp, "Nrrd ... ", output) imp = None img = None img2 = None gc.collect() time.sleep(15) gc.collect() IJ.run("Collect Garbage", "") IJ.run("Collect Garbage", "")
def scaleandfilter(infile,outfile,scalex,scaley,scalez,anisofilter,runtube): print ("infile is: "+infile) imp = Opener().openImage(infile) print imp print "scalex = %f; scaley = %f ; scalez = %f" % (scalex,scaley,scalez) # Rescale cal = imp.getCalibration() iml = ImgLib.wrap(imp) scaledimg = Scale3D(iml, scalex, scaley, scalez) imp2=ImgLib.wrap(scaledimg) # find range of pixel values for scaled image from mpicbg.imglib.algorithm.math import ComputeMinMax # (for imglib2 will be: net.imglib2.algorithm.stats) minmax=ComputeMinMax(scaledimg) minmax.process() (min,max)=(minmax.getMin().get(),minmax.getMax().get()) # Make a copy of the stack (converting to 8 bit as we go) stack = ImageStack(imp2.width, imp2.height) print "min = %e, max =%e" % (min,max) for i in xrange(1, imp2.getNSlices()+1): imp2.setSliceWithoutUpdate(i) ip=imp2.getProcessor() # set range ip.setMinAndMax(min,max) stack.addSlice(str(i), ip.convertToByte(True)) # save copy of calibration info cal=imp.getCalibration() # close original image imp.close() # make an image plus with the copy scaled = ImagePlus(imp2.title, stack) # Deal with calibration info which didn't seem to come along for the ride cal.pixelWidth/=scalex cal.pixelHeight/=scaley cal.pixelDepth/=scalez scaled.setCalibration(cal) print "dx = %f; dy=%f; dz=%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth) intif=infile+".tif" outtif=infile+"-filtered.tif" if anisofilter.upper() != 'FALSE': print("saving input file as "+intif) f=FileSaver(scaled) f.saveAsTiffStack(intif) scaled.close() # anisotropic filtering anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0" anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth) if sys.version_info > (2, 4): #for testing # subprocess.check_call(["cp",intif,outtif]) subprocess.check_call([anisofilter]+anisopts.split(' ')+[intif,outtif]) else: os.system(" ".join([anisofilter]+anisopts.split(' ')+[intif,outtif])) # Open anisofilter output back into Fiji print("Opening output tif: "+outtif) scaled = Opener().openImage(outtif) scaled.setCalibration(cal) # Hessian (tubeness) print("Running tubeness") if(runtube): tp=TubenessProcessor(1.0,False) result = tp.generateImage(scaled) IJ.run(result, "8-bit","") else: result=scaled # Save out file fileName, fileExtension = os.path.splitext(outfile) print("Saving as "+fileExtension+": "+outfile) if fileExtension.lower()=='.nrrd': nw=Nrrd_Writer() nw.setNrrdEncoding("gzip") nw.save(result,outfile) else: # Save to PIC IJ.run(result,"Biorad ...", "biorad=["+outfile+"]") scaled.close() result.close()
from net.imglib2.img.display.imagej import ImageJFunctions from net.imglib2.view import Views from itertools import imap from java.lang import System from net.imglib2.roi import EllipseRegionOfInterest from net.imglib2 import Point, RealPoint cell_diameter = 5 # in microns minPeak = 40 # The minimum intensity for a peak to be considered so. imp = IJ.getImage( ) #IJ.openImage("http://pacific.mpi-cbg.de/samples/first-instar-brain.zip") # Scale the X,Y axis down to isotropy with the Z axis cal = imp.getCalibration() scale2D = cal.pixelWidth / cal.pixelDepth iso = Compute.inFloats(Scale2D(Red(ImgLib.wrap(imp)), scale2D)) #ImgLib.wrap(iso).show() # Find peaks by difference of Gaussian sigma = (cell_diameter / cal.pixelWidth) * scale2D peaks = DoGPeaks(iso, sigma, sigma * 0.5, minPeak, 1) print "Found", len(peaks), "peaks" # Copy ImgLib1 iso image into ImgLib2 copy image copy = ArrayImgFactory().create( [iso.getDimension(0), iso.getDimension(1), iso.getDimension(2)], FloatType()) c1 = iso.createCursor() c2 = copy.cursor() while c1.hasNext():
# If minPeak is set to 0, set it to automatically. if minPeak == 0: minPeak = AutoThresholder().getThreshold("Percentile", imp.getStatistics().histogram); #Get the pixel calibration cal=imp.getCalibration() #Set Gaussian Sigma parameters for the Difference of Gaussian sigmaLarge=[cellDiameter/cal.pixelWidth,cellDiameter/cal.pixelHeight,cellDiameter/cal.pixelDepth] sigmaSmall=[a/2 for a in sigmaLarge] print "Cell Diameter: XY-%f Z-%f in pixel" % (cellDiameter/cal.pixelWidth, cellDiameter/cal.pixelDepth) print "Minimum peak value: %f" % (minPeak) print "Sigma Large : %f %f %f in pixel" % (cellDiameter/cal.pixelWidth, cellDiameter/cal.pixelHeight,cellDiameter/cal.pixelDepth) print "Sigma Small : %f %f %f in pixel" % (cellDiameter/cal.pixelWidth/2, cellDiameter/cal.pixelHeight/2,cellDiameter/cal.pixelDepth/2) #peaks=DoGPeaks(Red(ImgLib.wrap(imp)),sigmaLarge,sigmaSmall,minPeak,1) #Difference of Gaussians peaks=DoGPeaks(ImgLib.wrap(imp),sigmaLarge,sigmaSmall,minPeak,1) print "Found", len(peaks), "peaks" ######################################################### # Show the peaks as spheres in 3D, along with orthoslices ######################################################### #Get point list from the DoGPeaks rescaled according to the pixel size points = peaks.asPoints([cal.pixelWidth,cal.pixelHeight,cal.pixelDepth]) #Sort the coordinate on x axis points = sorted(points, key=lambda point: point.x) #Write all points in a text file for point in points:
from script.imglib.math import Compute, Subtract from script.imglib.color import Red, Green, Blue, RGBA from script.imglib import ImgLib from ij import IJ # RGB image stack 열기 imp = IJ.openImage("https://imagej.nih.gov/ij/images/flybrain.zip") # Wrap it as an Imglib image img = ImgLib.wrap(imp) # Example 1: subtract red from green channel sub = Compute.inFloats(Subtract(Green(img), Red(img))) ImgLib.wrap(sub).show() # Example 2: subtract red from green channel, and compose a new RGBA image rgb = RGBA(Red(img), Subtract(Green(img), Red(img)), Blue(img)).asImage() ImgLib.wrap(rgb).show()
with a helpful name. """ from script.imglib.math import Compute, Divide, Multiply, Subtract from script.imglib.algorithm import Gauss, Scale2D, Resample from script.imglib import ImgLib from ij import IJ, WindowManager # Start Clean IJ.run("Close All") # 1. Open an image imp = IJ.openImage("https://imagej.nih.gov/ij/images/bridge.gif") ti = imp.getShortTitle() img = ImgLib.wrap(imp) # 2. Simulate a brighfield from a Gauss with a large radius # (First scale down by 4x, then gauss of radius=20, then scale up) brightfield = Resample(Gauss(Scale2D(img, 0.25), 20), img.getDimensions()) # 3. Simulate a perfect darkfield darkfield = 0 # 4. Compute the mean pixel intensity value of the image mean = reduce(lambda s, t: s + t.get(), img, 0) / img.size() # 5. Correct the illumination corrected = Compute.inFloats(Multiply(Divide(Subtract(img, brightfield), Subtract(brightfield, darkfield)), mean))
def detect_objects_3D(imp, size, i, zmin, zmax): test = [] cdf = [] IJ.run("3D OC Options", " nb_of_obj._voxels median_gray_value centroid dots_size=5 font_size=10 store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=none"); #ip = imp.getProcessor() #print "grabbing image..." #test = ip.getHistogram() #test = StackStatistics(imp).getHistogram() #print "calculating stack statistics..." #total = sum(test) #print "calculate threshold" #cdf = map(lambda x: x/float(total), acc(test)) #thresh = min(filter(lambda x: cdf[x] >= quantile, xrange(1,len(cdf)) )) max_int = StackStatistics(imp).max cal= imp.getCalibration() scale2D = cal.pixelWidth / cal.pixelDepth sigma = (size / cal.pixelWidth) * scale2D iso = Compute.inFloats(Scale2D(ImgLib.wrap(imp),scale2D)) #thresh = 0 thresh = round(max_int/25.5) peaks = DoGPeaks(iso, sigma, sigma * 0.5, thresh, 1) ps = [] # print max_int # for p in peaks: # if p[2]>zmin and p[2]<zmax: # p2 = Point3f(p) # p2.scale(cal.pixelWidth * 1/scale2D) # ps.append(p2) #ob3d = Counter3D(imp, thresh) #peaks = ob3d.getCentroidList() print "FOund", len(peaks), "peaks" #ps = [] file = open(folder+exp_name+'/'+'cells/'+str(i).zfill(4)+'_cells.csv','w') exporter = csv.writer(file) #TODO: check consistency of coordinates ! for peak in peaks: print peak[2] if peak[2]>=zmin and peak[2]<=zmax: #print "raw",peak p = Point3f(peak) p.scale(cal.pixelWidth * 1./scale2D) #print "sf", cal.pixelWidth * 1/scale2D #print "scaled", p ps.append(p) t = () exporter.writerow([p.x, p.y, p.z]) file.close()
from script.imglib.math import Compute, Add, Subtract from script.imglib.color import HSB, Hue, Saturation, Brightness from script.imglib import ImgLib from ij import IJ # Obtain an image img = ImgLib.wrap(IJ.openImage("https://imagej.nih.gov/ij/images/clown.jpg")) # Obtain a new clown, whose hue has been shifted by half # with the same saturation and brightness of the original bluey = Compute.inRGBA( HSB(Add(Hue(img), 0.5), Saturation(img), Brightness(img))) print type(Hue(img)), type(Saturation(img)), type(Brightness(img)) ImgLib.wrap(Compute.inFloats(Hue(img))).show() ImgLib.wrap(Compute.inFloats(Saturation(img))).show() ImgLib.wrap(Compute.inFloats(Brightness(img))).show() ImgLib.wrap(bluey).show()
from script.imglib.math import Compute, Subtract, Multiply from script.imglib.color import Red, Blue, RGBA from script.imglib.algorithm import Gauss, Dither from script.imglib import ImgLib from ij import IJ # Obtain a color image from the ImageJ samples clown = ImgLib.wrap(IJ.openImage("https://imagej.nih.gov/ij/images/clown.jpg")) # Example 1: compose a new image manipulating the color channels of the clown image: img = RGBA(Gauss(Red(clown), 10), 40, Multiply(255, Dither(Blue(clown)))).asImage() print type(img) ImgLib.wrap(img).show()
# Flat-field correction: Flat-field correction is a technique used to improve quality in digital imaging. The goal is to remove artifacts from 2-D images that are caused by variations in the pixel-to-pixel sensitivity of the detector and/or by distortions in the optical path. It is a standard calibration procedure in everything from pocket digital cameras to giant telescopes. # very large radius의 median을 실행해서 flat-field image를 simulation할 수 있으나, computing cost가 높아 대신 scale down된 image에 Gauss를 적용하고 원본 이미지만큼 scale up. # 결과물 이상함. 추후 코드 확인 및 수정 from script.imglib.math import Compute, Divide, Multiply, Subtract from script.imglib.algorithm import Gauss, Scale2D, Resample from script.imglib import ImgLib from ij import IJ # 1. Open an image img = ImgLib.wrap(IJ.openImage("https://imagej.nih.gov/ij/images/bridge.gif")) ImgLib.wrap(img).show() # 2. Simulate a bright field from a Gauss with a large radius # (First scale down by 4x, then gauss of radius=20, then scale up) brightfield = Resample(Gauss(Scale2D(img, 0.25), 20), img.getDimensions()) _bf = Compute.inFloats(brightfield) ImgLib.wrap( _bf).show() # 회색으로 보이지만 ImageJ가 range를 -3.4e3 ~ 3.4e38로 인식해서 발생하는 문제임. # 3. Simulate a perfect darkfield darkfield = 0 # 4. Compute the mean pixel intensity value of the image mean = reduce(lambda s, t: s + t.get(), img, 0) / img.size() # 5. Correct the illumination corrected = Compute.inFloats( Multiply( Divide(Subtract(img, brightfield), Subtract(brightfield, darkfield)), mean))
imp = WindowManager.getCurrentImage() #imp = IJ.openImage("http://pacific.mpi-cbg.de/samples/first-instar-brain.zip") #imageStats = imp.getStatistics() #imageMin = imageStats.min() imageMin = imp.MIN_MAX print 'min:', imageMin # Scale the X,Y axis down to isotropy with the Z axis cal = imp.getCalibration() print ' x/y/z calibration is: ', cal.pixelWidth, cal.pixelHeight, cal.pixelDepth scale2D = cal.pixelWidth / cal.pixelDepth print ' calling scale2d' #iso = Compute.inFloats(Scale2D(Red(ImgLib.wrap(imp)), scale2D)) iso = Compute.inFloats(Scale2D(ImgLib.wrap(imp), scale2D)) # Find peaks by difference of Gaussian sigma = (cell_diameter / cal.pixelWidth) * scale2D print ' starting dogpeaks...' peaks = DoGPeaks(iso, sigma, sigma * 0.5, minPeak, 1) print " Found", len(peaks), "peaks" # Convert the peaks into points in calibrated image space if len(peaks)>0: ps = [] for peak in peaks: p = Point3f(peak) p.scale(cal.pixelWidth * 1/scale2D) ps.append(p)