0

I'm trying to pass the selection_variable.get() to the args dict for the run_macro function below such that the Mag variable in the counter_macro (in java for ImageJ) changes to that selection variable. It works with int(input("Mag?"), but not as a tk.radiobutton.

I can pass it properly prior without tkinter, but making a function that calls the macro via a button click does not allow the value to pass. I've tried redefining it as a string in the macro arguments and parsing it, but I persistently get the error:

Statement cannot begin with '#' in line 4.

Which is the input variable initialization.

I use Jupyter so my code is broken up.

# Imports
import scyjava as sj
from skimage import io
from IPython.display import Image
import os
import pandas as pd
# GUI Imports
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox as mb
import tkinter.font as tkFont
# More Imports
import imagej
# Initialize ImageJ
import scyjava
scyjava.config.add_options('-Xmx6g')
ij = imagej.init('sc.fiji:fiji',add_legacy=True, mode='interactive')
print(f"ImageJ version: {ij.getVersion()}")
ij.getApp().getInfo(True)
def open_file():
    file = filedialog.askopenfilename(title="Open Image File for ImageJ",
    filetypes=[
        ("Image files", "*.tif *.tiff *.png *.jpg *.jpeg *.gif *.bmp *.raw *.lsm *.nd2"),
        ("TIFF files", "*.tif *.tiff"),
        ("PNG files", "*.png"),
        ("JPEG files", "*.jpg *.jpeg"),
        ("GIF files", "*.gif"),
        ("BMP files", "*.bmp"),
        ("Raw files", "*.raw"),
        ("Confocal files (LSM)", "*.lsm"),
        ("Nikon files (ND2)", "*.nd2"),
        ("All files", "*.*")
    ]
)
    if file:
        basename = os.path.basename(file)
        # dataset = ij.io().open(path)
        # ij.py.show(dataset)
        ij.ui().showUI()
        IJ = sj.jimport('ij.IJ')
        ImageConverter = sj.jimport('ij.process.ImageConverter')
        output_string.set('File selected is: ' + basename)
        file_section.pack()
        imp = IJ.openImage(file)
        ic = ImageConverter(imp)
        ic.convertToGray8()
        ij.ui().show(imp)
    else:
        output_string.set('No File Selected, please choose a file.')
        
def clicked():
    Mag_Label.config(text=str(selected_option.get())+'x Magnification chosen.')

def run_macro(mag_choice):
    base.lower()
    counter_macro = """
    //Make 8-bit for thresholding
    //This code is meant to count single tiny crystals. Use Grain_counter for grain counting in large crystals.
    #@ int Mag
    if (Mag==5) {
        ScaleSize = 1000;
    } else if (Mag==10){
        ScaleSize = 500;
    } else if (Mag==20){
        ScaleSize = 250;
    } else if (Mag==50){
        ScaleSize = 100;
    } else {
        ScaleSize = 50;
    }
    window = getTitle();
    setTool("line");
    waitForUser("Draw a straight line over your scale bar and click 'OK'. Your magnification determines this conversion. ");
    getLine(x1,y1,x2,y2,lineWidth);
    waitForUser("Your selected magnification is: "+Mag + "x.");
    run("Set Scale...","distance=1150 known=ScaleSize");
    //Crop out your scale bar
    rec_x = x1-40;
    rec_y=y1-60;
    makeRectangle(rec_x,rec_y,1200,150);
    run("Clear");
    run("Select None");
    //Thresholding
    setAutoThreshold("Default");
    run("Threshold...");
    setThreshold(200, 255, "raw");
    //run("Convert to Mask");
    //run("Watershed");
    //Counting
    run("Set Measurements...", "area display redirect=None decimal=1");
    run("Analyze Particles...", "size=10-Infinity show=Outlines display overlay");
    showMessage("Save your drawing for checking later");
    saveAs("PNG");
    close();
    selectWindow(window);
    showMessage("Save your binary image for checking later.");
    saveAs("PNG");
    close();
    selectWindow("Threshold");
    run("Close");
    selectWindow("Results");
    showMessage("Your results have been copied into a matrix in python.");
    run("Clear Results");
    """
    # df = pd.DataFrame()
    args = {"Mag": mag_choice}
    result = ij.py.run_macro(counter_macro, args)
    result_table = ij.ResultsTable.getResultsTable()
    df = ij.py.from_java(result_table)

    # if df.empty():
    #     args={"Mag": mag_selection()}
    #     result = ij.py.run_macro(counter_macro, args)
    #     result_table = ij.ResultsTable.getResultsTable()
    #     df = ij.py.from_java(result_table)
    # else:
    #     args={"Mag": mag_selection()}
    #     result = ij.py.run_macro(counter_macro, args)
    #     result_table = ij.ResultsTable.getResultsTable()
    #     df = ij.py.from_java(result_table)

# Open a window
base = tk.Tk()
base.title('Image Analysis Tool')
base.geometry('1000x600')
ForCollin = tkFont.Font(family='Comic Sans MS')
s = ttk.Style()
s.configure('TButton', font=('Comic Sans MS',12))
ws = ttk.Style()
ws.configure('YH.TLabel',font=('Chiller',30, 'italic'),background='yellow')
base.option_add('*Font',ForCollin)

# Make a sub-window
main_frame = tk.Frame(base)
main_frame.pack(pady=10)
title_label = ttk.Label(master = base, text = 'Select your data',font=('Comic Sans MS',24, 'bold'))
title_label.pack(pady=10)
open_file_button = ttk.Button(base, text = 'Choose file', style='TButton',command=open_file)
open_file_button.pack(pady=10)
output_string = tk.StringVar()
output_label = ttk.Label(
    base, 
    text = 'Choose file...', 
    textvariable= output_string)
output_label.pack(pady=5)

# Once you open a file
file_section = ttk.Frame(base)
selected_option = tk.IntVar()
selected_option.set(0)
r1 = tk.Radiobutton(base, text="5x Objective", variable=selected_option, value=5, command=clicked)
r1.pack(pady=5)
r2 = tk.Radiobutton(base, text="10x Objective", variable=selected_option, value=10, command=clicked)
r2.pack(pady=5)
r3 = tk.Radiobutton(base, text="20x Objective", variable=selected_option, value=20, command=clicked)
r3.pack(pady=5)
r4 = tk.Radiobutton(base, text="50x Objective", variable=selected_option, value=50, command=clicked)
r4.pack(pady=5)
r5 = tk.Radiobutton(base, text="100x Objective", variable=selected_option, value=100, command=clicked)
r5.pack(pady=5)
Mag_Label = ttk.Label(base, text="Select your image magnification")
Mag_Label.pack(pady=10)


Submit_button = ttk.Button(base, text = 'Process Image', style='TButton',command=run_macro(selected_option.get()))
Submit_button.pack(pady=5)

warning_label = ttk.Label(file_section, text = 'CLOSE THIS WINDOW BEFORE STOPPING CODE!', style='YH.TLabel', font=('Chiller',30, 'italic'))
warning_label.pack(pady=5)

base.mainloop()

This is the code that I know works, but I don't know why passing an integer from a radio buttons is different from an integer-casted input.

path = "C:/path/to/png"
basename = os.path.basename(path)
ij.ui().showUI()
IJ = sj.jimport('ij.IJ')
ImageConverter = sj.jimport('ij.process.ImageConverter')
imp = IJ.openImage(path)
ic = ImageConverter(imp)
ic.convertToGray8()
ij.ui().show(imp)
counter_macro = """
//Make 8-bit for thresholding
//This code is meant to count single tiny crystals. Use Grain_counter for grain counting in large crystals.
#@ int Mag
if (Mag==5) {
    ScaleSize = 1000;
} else if (Mag==10){
    ScaleSize = 500;
} else if (Mag==20){
    ScaleSize = 250;
} else if (Mag==50){
    ScaleSize = 100;
} else {
    ScaleSize = 50;
}
window = getTitle();
setTool("line");
waitForUser("Draw a straight line over your scale bar and click 'OK'. Your magnification determines this conversion. ");
getLine(x1,y1,x2,y2,lineWidth);
waitForUser("Your selected magnification is: "+Mag + "x.");
run("Set Scale...","distance=1150 known=ScaleSize");
//Crop out your scale bar
rec_x = x1-40;
rec_y=y1-60;
makeRectangle(rec_x,rec_y,1200,150);
run("Clear");
run("Select None");
//Thresholding
setAutoThreshold("Default");
run("Threshold...");
setThreshold(200, 255, "raw");
//Counting
run("Set Measurements...", "area display redirect=None decimal=1");
run("Analyze Particles...", "size=10-Infinity show=Outlines display overlay");
showMessage("Save your drawing for checking later");
saveAs("PNG");
close();
selectWindow(window);
showMessage("Save your binary image for checking later.");
saveAs("PNG");
close();
selectWindow("Threshold");
run("Close");
selectWindow("Results");
""" 
args = {"Mag": int(input('What mag is it?'))}
result = ij.py.run_macro(counter_macro, args)
result_table = ij.ResultsTable.getResultsTable()
df = ij.py.from_java(result_table)

Attached is the image that I've been troubleshooting with. sample on substrate

3
  • 2
    Note that command=run_macro(selected_option.get()) will execute run_macro() immediately, not when the button is clicked. Use command=lambda: run_macro(selected_option.get()) instead. Commented Jul 22 at 23:46
  • @acw1668 I tried that, but nothing changed. I still get the imagej macro error for #@ int Mag Commented Jul 23 at 13:33
  • Although it is not the cause of your issue, but it is still an issue needed to be fixed. Commented Jul 23 at 15:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.