ImageJ编程:macro插件教程(1)

2,372 阅读2分钟

本人不会java,单位要求开发一个插件,但是ImageJ的插件是Java写的,为了减少学习成本,曲线救国,使用ImageJ自带的Macro做一个能够和python写的后端代码交互的入口,并在ImageJ启动面板上显示相应的图形按钮。

前端效果

上图中的自定义按钮如果要ImageJ启动的时候就能显示,那么就需要把你的macro脚本插入到Macros目录下的StartupMacros.fiji.ijm中。

需要注意的是,如果你是一个Menu Tool,则需要在插入的macro代码段前面定义Menu,格式如newMenu("Menu Name", newArray("key1","key2",...))

然后的你Menu Tool还可以有一个图标,这个图标的生成颇费功夫,但是ImageJ官方提供了一个小工具,也是一段macro代码,能够将16x16大小的8 bit 图像(推荐使用不超过16色)转换为图标代码,如下所示。把这段代码复制保存为后缀为ijm的文件,然后直接从ImageJ>Plugins>Macros>Install,安装这个ijm文件即可。

// This macro converts a 16x16 8-bit image to a tool macro icon
// string. Ideally, the image should have no more than 16 colors.
// Includes seven examples that, with the exception of the 
// "Lena Tool", were created by converting website favicons
// (http://en.wikipedia.org/wiki/Favicon).

macro "Convert Image to Tool Icon..." {
    requires("1.35r");
    if (bitDepth!=8 || getWidth>16 || getHeight>16)
       exit("This macro requires 16x16 8-bit image");
    Dialog.create("Image 2 Tool");
    Dialog.addString("Tool name", "myTool");
    Dialog.addCheckbox("Transparent Color", true);
    Dialog.addNumber("Value", 0);
    Dialog.show();
    mytool = Dialog.getString();
    allPixels = !Dialog.getCheckbox();
    transparent = Dialog.getNumber();
    getLut(r,g,b);
    getRawStatistics(area, mean, min, max);
    ts='macro "'+mytool+' Tool - ';
    for (i=0; i<=max; i++) {
        if (allPixels || i!=transparent) {
            r2=floor(r[i]/256*16);
            g2=floor(g[i]/256*16);
            b2=floor(b[i]/256*16);
            color = "C"+toHex(r2)+toHex(g2)+toHex(b2);
            if (!endsWith(ts, color)) ts=ts+color;
            for (x=0; x<getWidth; x++) {
                for (y=0; y<getHeight; y++) {
                    if (getPixel(x,y)==i)
                        ts=ts+"D"+toHex(x)+toHex(y);
                }
            }
        }
    }
    ts=ts+'"{\n\n}';
    macrodir = getDirectory("macros");
    if (!endsWith(mytool,".txt")) mytool = mytool+".txt";
    f = File.open(macrodir+mytool);
    print (f, ts);
    File.close(f);
    open(macrodir+mytool);
  }

你需要先建立一个RGB的图像,使用不超过16中颜色绘制一张图,然后把大小调整到16x16仍然看上去清晰,然后转化成8 bit color的图。然后运行上面的macro,即可生成一堆乱码的东西。