Last active
May 9, 2019 10:22
-
-
Save miura/a42539a5a19a7f146572fcbb50e1f004 to your computer and use it in GitHub Desktop.
IJ macro course codes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//variables | |
a = 1; | |
b = 2; | |
c = a + b; | |
print("\\Clear"); | |
print( c ); | |
print(a, "+", b, "=", c); | |
//variables, exercise, an example answer | |
a = 1; | |
b = 2; | |
c = a + b * 2 + a/0.1 - 2; | |
print("\\Clear"); | |
print( c ); | |
//print(a, "+", b, "=", c); | |
//user input, numerical variable | |
a = getNumber("a?", 10); | |
b = getNumber("b?", 5); | |
c = a * b; | |
print("\\Clear"); | |
print(c); | |
//user input, String variable | |
a = getString("a?", 10); | |
b = getString("b?", 5); | |
c = a + b; | |
print("\\Clear"); | |
print(c); | |
//script parameters | |
#@ String(label="Word1") text1 | |
#@ String(label="Word2") text2 | |
text3 = text1 + text2; | |
print( text3 ); | |
//*** recording ImageJ macro and modifying the macro | |
newImage("Untitled", "8-bit Black", 300, 300, 1); | |
run("Salt and Pepper"); | |
run("Gaussian Blur...", "sigma=3"); | |
setAutoThreshold("Default dark"); | |
setOption("BlackBackground", true); | |
run("Convert to Mask"); | |
// extract variables | |
width = 300; | |
title = "Noisy_Image" | |
newImage(title, "8-bit Black", width, 300, 1); | |
run("Salt and Pepper"); | |
run("Gaussian Blur...", "sigma=3"); | |
setAutoThreshold("Default dark"); | |
setOption("BlackBackground", true); | |
run("Convert to Mask"); | |
run("Erode"); | |
// for-looping | |
width = 300; | |
title = "Noisy_Image" | |
newImage(title, "8-bit Black", width, 300, 1); | |
run("Salt and Pepper"); | |
run("Gaussian Blur...", "sigma=3"); | |
setAutoThreshold("Default dark"); | |
setOption("BlackBackground", true); | |
run("Convert to Mask"); | |
for (i = 0; i < 3; i+=1){ | |
run("Erode"); | |
} | |
//****** for-looping, scanning through image | |
// measure single pixel | |
val = getPixel( 10, 10); | |
print( val ); | |
// parameterizing measurements | |
x = 10; | |
y = 10; | |
val = getPixel( x, y); | |
print( val ); | |
// for-looping to measure more pixels | |
for (i = 0; i < 50; i++) { | |
x = i; | |
y = 10; | |
val = getPixel( x, y); | |
print( val ); | |
} | |
//// counting, with "if" | |
c255 = 0; | |
for (i = 0; i < 50; i++) { | |
x = i; | |
y = 10; | |
val = getPixel( x, y); | |
if ( val == 0) { | |
c255 +=1; | |
} | |
} | |
print( "255 counts:", c255 ); | |
// scanning through full image to count pixels with a specific value | |
c255 = 0; | |
for (j = 0; j < getHeight(); j++){ | |
for (i = 0; i < getWidth(); i++){ | |
val = getPixel( i, j); | |
if (val == 255){ | |
c255 += 1; | |
} | |
} | |
} | |
print("255 counts:", c255); | |
//*** user defined function | |
a = 4; | |
b = a * a * a * a; | |
print(b); | |
// step 2 | |
a = 4; | |
b = compute( a ); | |
print(b); | |
function compute( num ){ | |
p4 = num * num * num * num; | |
return p4; | |
} | |
// step 3 | |
a = 4; | |
b = differentone( a ); | |
print(b); | |
function compute( num ){ | |
p4 = num * num * num * num; | |
return p4; | |
} | |
function differentone( num ){ | |
p4 = num * num * num * num * num; | |
return p4; | |
} | |
//step 4 | |
a = 4; | |
c = 2; | |
b = compute( a, c ); | |
print(b); | |
function compute( num1, num2 ){ | |
p4 = num1 * num2 * num1 * num2; | |
return p4; | |
} | |
//*** Stack Management | |
frames = nSlices; | |
run("Set Measurements...", " mean redirect=None decimal=3"); | |
run("Clear Results"); | |
for(i=0; i<frames; i++) { | |
currentslice = i+1; | |
setSlice(currentslice); | |
run("Measure"); | |
} | |
//Stack Management, exercise answer example | |
frames = nSlices; | |
run("Set Measurements...", " mean min centroid redirect=None decimal=3"); | |
run("Clear Results"); | |
for(i=0; i<frames; i++) { | |
currentslice = i+1; | |
setSlice(currentslice); | |
run("Measure"); | |
} | |
//multiple ROIs | |
run("Clear Results"); | |
roinum = roiManager("count"); | |
for (index = 0; index < roinum; index++) { | |
roiManager("select", index); | |
run("Measure"); | |
} | |
// stack management * multiple ROIs | |
run("Clear Results"); | |
roinum = roiManager("count"); | |
for (index = 0; index < roinum; index++) { | |
roiManager("select", index); | |
measureStack(); | |
} | |
function measureStack(){ | |
frames = nSlices; | |
run("Set Measurements...", " mean min centroid redirect=None decimal=3"); | |
//run("Clear Results"); | |
for(i=0; i<frames; i++) { | |
currentslice = i+1; | |
setSlice(currentslice); | |
run("Measure"); | |
} | |
} | |
//*** array, accessing Results Table | |
aa = newArray(nResults); | |
for (i = 0; i < aa.length; i++){ | |
aa[i] = getResult("Min", i); | |
} | |
Array.getStatistics(aa, min, max, mean, stdDev); | |
print("Average of Min = ", min); | |
//exercise: prep 1 to 10 array, get the average | |
aa = newArray(10); | |
for ( i = 0; i < aa.length; i++){ | |
aa[i] = i + 1; | |
} | |
Array.getStatistics(aa, min, max, mean, stdDev); | |
print("Mean of the array", mean); | |
// array and setting results table | |
if (selectionType() != 5) { | |
exit("selection type must be a straight line ROI"); | |
} | |
lineProfile = getProfile(); | |
run("Clear Results"); | |
for(i = 0; i < lineProfile.length; i++) { | |
setResult("n", i, i); | |
setResult("intensity", i, lineProfile[i]); | |
} | |
updateResults(); | |
//User interface, Dialog | |
Dialog.create("add two numbers"); | |
Dialog.addMessage("Computes x + y"); | |
Dialog.addNumber("x", 10); | |
Dialog.addNumber("y", 20); | |
Dialog.show(); | |
n1 = Dialog.getNumber(); | |
n2 = Dialog.getNumber(); | |
print("Results:", n1 + n2); | |
//UI exercies | |
Dialog.create("Distance Calculator"); | |
Dialog.addMessage("Please put two point coordinates"); | |
Dialog.addNumber("p1 x", 0); | |
Dialog.addNumber("p1 y", 0); | |
Dialog.addNumber("p2 x", 10); | |
Dialog.addNumber("p2 y", 20); | |
Dialog.show(); | |
p1x = Dialog.getNumber(); | |
p1y = Dialog.getNumber(); | |
p2x = Dialog.getNumber(); | |
p2y = Dialog.getNumber(); | |
print("P1(", p1x, ",", p1y, ")"); | |
print("P2(", p2x, ",", p2y, ")"); | |
dist = sqrSumSquared(p1x, p1y, p2x, p2y); | |
print("Distance:", dist); | |
function sqrSumSquared(x1, y1, x2, y2){ | |
sumsquared = pow(x1-x2, 2) + pow(y1-y2, 2); | |
return pow(sumsquared, 0.5); | |
} | |
//*** dot animation | |
newImage("dot", "8-bit Black", 200, 50, 2); | |
setForegroundColor(255, 255, 255); | |
setBackgroundColor(0, 0, 0); | |
makeOval( 100, 25, 10, 10); | |
run("Fill", "slice"); | |
// dot animation with variables | |
stackname = "dot"; | |
w = 250; | |
h = 50; | |
frames = 2; | |
int = 255 | |
x_position = 100; | |
y_position = 25; | |
sizenum = 10; | |
newImage(stackname, "8-bit Black", w, h, frames); | |
setForegroundColor(int, int, int); | |
setBackgroundColor(0, 0, 0); | |
makeOval(x_position, y_position, sizenum, sizenum); | |
run("Fill", "slice"); | |
// dot animation, no bouncing case | |
stackname = "dot"; | |
w = 250; | |
h = 50; | |
frames = 50; | |
sizenum = 10; | |
int = 255 | |
x_position = sizenum; | |
y_position = (h/2)-(sizenum/2); | |
newImage(stackname, "8-bit Black", w, h, frames); | |
setForegroundColor(int, int, int); | |
setBackgroundColor(0, 0, 0); | |
speed = 10; | |
for (i = 0; i < frames; i++){ | |
setSlice( i + 1); | |
makeOval(x_position, y_position, sizenum, sizenum); | |
x_position += speed; | |
run("Fill", "slice"); | |
} | |
// boucing dot animation | |
stackname = "dot"; | |
w = 250; | |
h = 50; | |
frames = 50; | |
sizenum = 10; | |
int = 255 | |
x_position = sizenum; | |
y_position = (h/2)-(sizenum/2); | |
newImage(stackname, "8-bit Black", w, h, frames); | |
setForegroundColor(int, int, int); | |
setBackgroundColor(0, 0, 0); | |
speed = 10; | |
for (i = 0; i < frames; i++){ | |
setSlice( i + 1); | |
if ((x_position > (w-sizenum)) || (x_position < 0) ) { | |
speed*=-1; | |
x_position += speed*2; //avoids penetrating boundary | |
} | |
makeOval(x_position, y_position, sizenum, sizenum); | |
x_position += speed; | |
run("Fill", "slice"); | |
} | |
run("Select None"); | |
// exercise, vertical movement | |
stackname = "dot"; | |
w = 250; | |
h = 250; | |
frames = 50; | |
sizenum = 10; | |
int = 255 | |
x_position = sizenum; | |
y_position = (h/2)-(sizenum/2); | |
newImage(stackname, "8-bit Black", w, h, frames); | |
setForegroundColor(int, int, int); | |
setBackgroundColor(0, 0, 0); | |
speed = 10; | |
for (i = 0; i < frames; i++){ | |
setSlice( i + 1); | |
if ((y_position > (h-sizenum)) || (y_position < 0) ) { | |
speed*=-1; | |
y_position += speed*2; //avoids penetrating boundary | |
} | |
makeOval(x_position, y_position, sizenum, sizenum); | |
y_position += speed; | |
run("Fill", "slice"); | |
} | |
run("Select None"); | |
// another way of looping, do while | |
counter=0; | |
while ( counter <= 90 ){ | |
print( counter ); | |
counter = counter + 10; | |
} | |
// do -while, evaluation that comes after. | |
counter=0; | |
do { | |
print( counter ); | |
counter += 10; | |
} while (counter < 0) | |
// File I/O | |
// code component, get directory | |
Ddir = getDirectory("Choose Destination Directory"); | |
print(Ddir); | |
// code component, get threshold | |
getThreshold(lower, upper); | |
if ( ( lower == -1 ) && ( upper == -1 ) ) { | |
exit("Image must be thresholded"); | |
} | |
setThreshold(lower, 255); | |
// code component, save results | |
Ddir = getDirectory("Choose Destination Directory"); | |
print(Ddir); | |
img_title = getTitle(); | |
run("Measure"); | |
dest_filename = img_title + "_measure.xls"; | |
fullpath = Ddir + dest_filename; | |
saveAs("Measurements", fullpath); | |
//code 21, auto save results | |
Ddir = getDirectory("Choose Destination Directory"); | |
print(Ddir); | |
getThreshold(lower, upper); | |
if ((lower==-1) && (upper==-1)) { | |
exit("Image must be thresholded"); | |
} | |
setThreshold(lower, 255); | |
img_title=getTitle(); | |
run("Set Measurements...", | |
"area mean centroid circularity slice limit redirect=None decimal=2"); | |
run("Analyze Particles...", | |
"size=10-Infinity circularity=0.50-1.00 show=Outlines display exclude clear stack"); | |
dest_filename = img_title+"_measure.xls"; | |
fullpath = Ddir + dest_filename; | |
saveAs("Measurements", fullpath); | |
//batch analysis - list files | |
source_dir = getDirectory("Choose the Directory where the file is"); | |
list = getFileList(source_dir); | |
for(i=0; i<list.length; i++) { | |
print(list[i]); | |
} | |
// filename extension cleaner | |
imgtitle = getTitle(); | |
print( imgtitle ); | |
print( indexOf( imgtitle, ".tif") ); | |
imgtitleNoext = substring(imgtitle, 0, indexOf( imgtitle, ".tif")); | |
print( imgtitleNoext ); | |
resultsfilename = imgtitleNoext + "_measurements.csv"; | |
print( resultsfilename ); | |
// code 23, batch analysis | |
//batch analysis Code 23 --------------------------------------------- | |
source_dir = getDirectory("Choose the Directory where the file is"); | |
out_dir = getDirectory("Choose the Directory to save files"); | |
list = getFileList(source_dir); | |
for(i=0; i<list.length; i++) { | |
NucAnalysis(list[i]); | |
} | |
function NucAnalysis(img_filename) { | |
fullpath_image = source_dir + img_filename; | |
open(fullpath_image); | |
sourceID = getImageID(); | |
setAutoThreshold("Li dark"); | |
img_title = getTitle(); | |
run("Set Measurements...", | |
"area mean centroid circularity slice limit redirect=None decimal=2"); | |
run("Analyze Particles...", | |
"size=10-Infinity circularity=0.50-1.00 show=Outlines display exclude clear stack"); | |
selectImage(sourceID); | |
close(); | |
dest_outlinename = img_title+"_outline.tif"; | |
fullpath = out_dir + dest_outlinename; | |
saveAs("tiff", fullpath); | |
close(); | |
dest_filename = img_title+"_measure.xls"; | |
fullpath = out_dir + dest_filename; | |
print(fullpath ); | |
saveAs("Measurements", fullpath); | |
} | |
/////// Trainable Weka Segmentation | |
// single | |
//Step 1: create path variables | |
inputdir = "/Users/miura/Dropbox/Courses/IJMacro/IJmacro_samples/CellsDividing"; | |
outputdir = "/Users/miura/Downloads/out"; | |
themodel = "/Users/miura/Dropbox/Courses/IJMacro/exampleWekaSegModel/classifier.model"; | |
//Step 2 Launch Trainable Segmentation Plugin | |
open(inputdir + File.separator + "Nucseq0010000.tif"); | |
imgid = getImageID(); | |
run("Trainable Weka Segmentation"); | |
wait(3000); | |
//Step 3 Load the classifier model | |
call("trainableSegmentation.Weka_Segmentation.loadClassifier", themodel); | |
//Step 4 Apply classifier to an image | |
image = "Nucseq0010021.tif"; | |
call("trainableSegmentation.Weka_Segmentation.applyClassifier", | |
inputdir, | |
image, | |
"showResults=false", | |
"storeResults=true", | |
"probabilityMaps=false", | |
outputdir); | |
// batch | |
//Step 1: create path variables | |
inputdir = "/Users/miura/Dropbox/Courses/IJMacro/IJmacro_samples/CellsDividing"; | |
outputdir = "/Users/miura/Downloads/out"; | |
themodel = "/Users/miura/Dropbox/Courses/IJMacro/exampleWekaSegModel/classifier.model"; | |
//Step 2 Launch Trainable Segmentation Plugin | |
open(inputdir + File.separator + "Nucseq0010000.tif"); | |
imgid = getImageID(); | |
run("Trainable Weka Segmentation"); | |
wait(3000); | |
//Step 3 Load the classifier model | |
call("trainableSegmentation.Weka_Segmentation.loadClassifier", themodel); | |
//Step 4 Batch processing | |
// get file list | |
files = getFileList(inputdir); | |
// looping for each file | |
for (i = 0; i < files.length; i++){ | |
if ( endsWith( files[i], ".tif")){ | |
call("trainableSegmentation.Weka_Segmentation.applyClassifier", | |
inputdir, | |
files[i], | |
"showResults=false", | |
"storeResults=true", | |
"probabilityMaps=false", | |
outputdir); | |
//clear memory, just be on the safe side | |
run("Collect Garbage"); | |
} | |
} | |
//cleanup | |
selectImage(imgid); | |
close(); | |
selectWindow("Trainable Weka Segmentation v3.2.32"); | |
close(); | |
/////// colocalization - pixel based | |
//use JaCOP recorder | |
run("Bio-Formats Importer", "open=/Users/miura/Dropbox/20190225_Stuttgart/IJmacro/samples/Stephan/S467D_1.czi autoscale color_mode=Default open_all_series rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT"); | |
run("Split Channels"); | |
run("JACoP ", "imga=C3-S467D_1.czi imgb=C4-S467D_1.czi thra=6068 thrb=8495 pearson mm cytofluo"); | |
//use JaCOP modified | |
path = "/Users/miura/" + | |
"Dropbox/20190225_Stuttgart/Coloc/colocExample/S467D_1.czi"; | |
run("Bio-Formats Importer", "open=" + path + | |
" color_mode=Default view=Hyperstack stack_order=XYCZT"); | |
srcImgName = getTitle(); | |
run("Split Channels"); | |
c1name = "C1-" + srcImgName; | |
c2name = "C2-" + srcImgName; | |
c3name = "C3-" + srcImgName; | |
c4name = "C4-" + srcImgName; | |
imga_th = 6068; | |
imgb_th = 8495; | |
run("JACoP ", "imga=" + c3name + " imgb=" + c4name + | |
" thra=" + imga_th + " thrb=" + imgb_th + " pearson mm"); | |
// list files | |
dirpath = getDirectory("Choose a Directory"); | |
filelist = getFileList(dirpath); | |
for (i = 0; i < filelist.length; i++) { | |
if (endsWith( filelist[ i ], "czi") ){ | |
print( filelist[ i ] ); | |
} | |
} | |
//JaCop Batch | |
dirpath = getDirectory("Choose a Directory"); | |
filelist = getFileList(dirpath); | |
for (i = 0; i < filelist.length; i++) { | |
if (endsWith( filelist[ i ], "czi") ){ | |
print( filelist[ i ] ); | |
doJacop( dirpath + filelist[ i ] ); | |
} | |
} | |
function doJacop( czipath ){ | |
path = czipath; | |
run("Bio-Formats Importer", "open=" + path + | |
" color_mode=Default view=Hyperstack stack_order=XYCZT"); | |
srcImgName = getTitle(); | |
run("Split Channels"); | |
c1name = "C1-" + srcImgName; | |
c2name = "C2-" + srcImgName; | |
c3name = "C3-" + srcImgName; | |
c4name = "C4-" + srcImgName; | |
imga_th = 6000; | |
imga_th = 8000; | |
run("JACoP ", "imga=" + c3name + " imgb=" + c4name + | |
" thra=" + imga_th + " thrb=93 pearson mm"); | |
selectWindow(c1name); | |
close(); | |
selectWindow(c2name); | |
close(); | |
selectWindow(c3name); | |
close(); | |
selectWindow(c4name); | |
close(); | |
} | |
//colocalzation - object based | |
//outline | |
// splitting and grab ImageIDs | |
// segmentation | |
// divide ch1 image by 2 | |
// get average of two segmented channels | |
// count each area | |
//output results | |
//fullcode | |
// splitting and grab ImageIDs | |
run("Duplicate...", "duplicate"); //keep the original | |
srcImageName = getTitle(); | |
run("Split Channels"); | |
c1name = "C1-" + srcImageName; | |
c2name = "C2-" + srcImageName; | |
selectWindow(c1name); | |
c1ID = getImageID(); | |
selectWindow(c2name); | |
c2ID = getImageID(); | |
// segmentation | |
selectImage( c1ID ); | |
run("Auto Threshold", "method=Otsu white"); | |
selectImage( c2ID ); | |
run("Auto Threshold", "method=Otsu white"); | |
// divide ch1 image by 2 | |
selectImage( c1ID ); | |
run("Divide...", "value=2.000"); | |
// get average of two segmented channels | |
//imageCalculator("Average create", "C1-PlusTIPs_z16.tif","C2-PlusTIPs_z16.tif"); | |
imageCalculator("Average create", c1ID, c2ID); | |
averageID = getImageID(); | |
// count each area | |
c1only = countPixels( 64 ); | |
c2only = countPixels( 127 ); | |
overlap = countPixels( 191 ); | |
//output results | |
print("Ch1 ratio: ", overlap / (overlap + c1only)); | |
print("Ch2 ratio: ", overlap / (overlap + c2only)); | |
//clean up | |
selectImage( c1ID ); | |
close(); | |
selectImage( c2ID ); | |
close(); | |
selectImage( averageID ); | |
close(); | |
// count the number of pixels with specific value | |
function countPixels( pixelvalue ){ | |
count = 0; | |
for (j = 0; j < getHeight(); j++){ | |
for (i = 0; i < getWidth(); i++){ | |
val = getPixel( i, j); | |
if (val == pixelvalue){ | |
count += 1; | |
} | |
} | |
} | |
print(pixelvalue, "counts:", count); | |
return count; | |
} | |
// complex dialogue | |
Dialog.create("Calculate Distance"); | |
Dialog.addMessage("Calculates distance between two points"); | |
Dialog.addNumber("point1 x:", 0); //number 1 | |
Dialog.addNumber("point1 y:", 0); //number 2 | |
Dialog.addNumber("point2 x:", 2); //number 3 | |
Dialog.addNumber("point2 y:", 2); //number 4 | |
Dialog.addNumber("Scale [um/pixel]:", 0.1); //number 5 | |
Dialog.addCheckbox("scale?", true); //check 1 | |
Dialog.show(); | |
p1x = Dialog.getNumber(); //1 | |
p1y = Dialog.getNumber(); //2 | |
p2x = Dialog.getNumber(); //3 | |
p2y = Dialog.getNumber(); //4 | |
scale = Dialog.getNumber(); //5 | |
scaleswitch = Dialog.getCheckbox(); | |
distance = CalcDistance(p1x, p1y, p2x, p2y); | |
if (scaleswitch) | |
distance *= scale; | |
print("p1:", p1x, ",", p1y); | |
print("p2:", p2x, ",", p2y); | |
if (scaleswitch) { | |
print("distance:" + distance + " [um]"); | |
} else { | |
print("distance:" + distance + " [pixels]"); | |
} | |
function CalcDistance(p1x, p1y, p2x, p2y) { | |
sum_difference_squared = pow((p2x - p1x),2) + pow((p2y - p1y),2); | |
distance = pow(sum_difference_squared, 0.5); | |
return distance; | |
} | |
// homework | |
grid( 400, 400); | |
diagonalLattice(); | |
gridDiagonal_byWhileLoop(); | |
function grid( ww, hh){ | |
//y = 1000; | |
//x = 400; | |
newImage("grid", "8-bit Black", ww, hh, 1); | |
setColor(100); | |
setLineWidth(2); | |
for(i = 20; i < ww; i += 20) | |
drawLine( i, 0, i, hh - 1); | |
for(j = 20; j < hh; j += 20) | |
drawLine( 0, j, ww - 1, j); | |
} | |
function diagonalLattice(){ | |
size = 400 | |
newImage("grid", "8-bit Black", size, size, 1); | |
ww = size; | |
hh = size; | |
for (i = 0; i < size; i += 20){ | |
drawLine(i, 0, 0, i); | |
drawLine(i, hh-1, ww-1, i); | |
} | |
for (i = 0; i < size; i += 20){ | |
drawLine(i, hh-1, 0, ww - 1 - i); | |
drawLine(i, 0, ww-1, ww - 1 - i); | |
} | |
} | |
function gridDiagonal_byWhileLoop(){ | |
ww = 300; | |
hh = 500; | |
newImage("diagonal grid", "8-bit black", ww, hh, 1); | |
cursor = 0; | |
gspacing = 10; | |
while (cursor < ww + hh){ | |
px1 = 0; | |
py1 = cursor; | |
px2 = cursor; | |
py2 = 0; | |
if (py1 > hh){ | |
py1 = hh; | |
px1 = cursor - hh;; | |
} | |
if (px2 > ww){ | |
px2 = ww; | |
py2 = cursor - ww; | |
} | |
drawLine(px1, py1, px2, py2); | |
cursor += gspacing; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment