Передача значений от Tkinter Gui к макросу ImageJ через Pyimagej в Python без подпроцессаPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Передача значений от Tkinter Gui к макросу ImageJ через Pyimagej в Python без подпроцесса

Сообщение Anonymous »

Я пытаюсь передать selection_variable.get () DICT ARGS для функции RUN_MACRO ниже, чтобы переменная MAG в CONGRE_MACRO (в Java для ImageJ) изменений в этой переменной выбора. Он работает с int (input («Mag?»), Но не как TK.RadioButton. '#' в строке 4. < /p>
, которая является инициализацией входной переменной. < /p>
Я использую Юпитер, поэтому мой код разбит.# 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
< /code>
# 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)
< /code>
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)

< /code>
# 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()
< /code>
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')
< /code>
imp = IJ.openImage(path)
ic = ImageConverter(imp)
ic.convertToGray8()
ij.ui().show(imp)
< /code>
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)
< /code>
Attached is the image that I've been troubleshooting with.
sample on substrate

Подробнее здесь: https://stackoverflow.com/questions/797 ... -without-s
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Передача вывода подпроцесса в GUI Live
    Anonymous » » в форуме Python
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Отправка BMP через розетку или трубу в ImageJ с помощью C ++
    Anonymous » » в форуме C++
    0 Ответы
    14 Просмотры
    Последнее сообщение Anonymous
  • ПРОБЛЕМЫ ПРЕДУПРЕЖДЕНИЯ GUI PYTHON GUI
    Anonymous » » в форуме Python
    0 Ответы
    95 Просмотры
    Последнее сообщение Anonymous
  • Создание кнопки возврата на моем калькуляторе Python Tkinter GUI
    Anonymous » » в форуме Python
    0 Ответы
    35 Просмотры
    Последнее сообщение Anonymous
  • Как показать Gui Python Tkinter на местном дисплее от Docker
    Anonymous » » в форуме Python
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»