EclipseでImageJのPlugin作成 -数値から画像を作る-
今回は、数値から画像データを作る。
但し、僕がざっくり調べた感じでは、何もない状態からでは数値から画像データを作れなかったので、
ここでは、既存の画像ファイルの数値を入れ替える方法で、数値から画像データを作ることにした。
コードは下記。
import java.awt.BorderLayout; import java.awt.FileDialog; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import ij.IJ; import ij.ImagePlus; import ij.plugin.PlugIn; import ij.process.ImageProcessor; public class Make_Image implements PlugIn, ActionListener { ImagePlus imp; //数値から画像を作る public void makeImage() { ImagePlus imp0 = IJ.openImage("開く画像のディレクトリとファイル名"); int h = imp0.getHeight(); int w = imp0.getWidth(); imp0.show(); //数値から画像を作るためのキャンバス imp = imp0.duplicate(); ImageProcessor ip = imp.getProcessor(); float count = 0; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { ip.putPixelValue(i, j, count); if (count > 65535) count = 0; count++; } } imp.show(); IJ.run(imp, "Enhance Contrast", "saturated=0.35"); } //画像を名前を付けて保存する public void saveImage () { String saveName = addName (); IJ.saveAs(imp, "Tiff", saveName); } //保存する場所と名前を取得する String addName () { FileDialog fd = new FileDialog (new Frame(), "Add Name", FileDialog.SAVE); fd.setVisible(true); String fullpath = fd.getDirectory() + fd.getFile(); fd.dispose(); return fullpath; } //コントローラーの作成 public void run (String arg) { JFrame frame = new JFrame ("Make"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds (100, 100, 120, 120); JButton makeButton = new JButton ("Make"); JButton saveButton = new JButton ("Save"); makeButton.addActionListener(this); saveButton.addActionListener(this); makeButton.setActionCommand("Make"); saveButton.setActionCommand("Save"); makeButton.setBounds(15, 20, 90, 30); saveButton.setBounds(15, 50, 90, 30); JPanel pane = new JPanel (); pane.add(makeButton); pane.add(saveButton); pane.setLayout(null); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.setVisible(true); } //ボタンを押した時の反応d @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Make")) { makeImage(); } else if (cmd.equals("Save")) { saveImage(); } } }
ここではテストとして、下記の部分でグラデーションを作っている。
for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { ip.putPixelValue(i, j, count); if (count > 65535) count = 0; count++; } }
このプログラムを実行すると、
のコントローラーが立ち上がり、Makeボタンを押すと、
数値から画像を作るためのキャンバスとなる画像が開き (ここでは、ImageJにあるClown画像の16bit グレーイメージを使用)、
同時に、上の様に数値から作られた画像ができる。Saveボタンを押すと、この作成した画像を名前を付けて保存できるようにした。