Show (Mat) image
In new release OpenCV 2.4.6, how can I display image ( Mat ) on window using JAVA. I couldn't find the JAVA method from API?
In new release OpenCV 2.4.6, how can I display image ( Mat ) on window using JAVA. I couldn't find the JAVA method from API?
hi, Ioanna, found this on my disk, hope it helps !
actually, showing an image in a window is a bit more involved in java, as you need a container for the window ( a Frame ), threading, etc.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.applet.*;
public final class pxl extends Applet implements Runnable {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
VideoCapture cap; // capture
byte [] b; // pixel bytes
BufferedImage image; // our drawing canvas
private Thread idx_Thread;
public pxl() {
init();
}
public void init()
{
cap = new VideoCapture(0); // 1st webcam
// boolean ok = cap.open("d:/video/cam9.asf");
}
public void start() {
if (idx_Thread == null) {
idx_Thread = new Thread(this);
idx_Thread.start();
}
}
public void stop() {
if (idx_Thread != null) {
idx_Thread.stop();
idx_Thread = null;
}
}
public void run() {
Mat m = new Mat();
while(true) {
if (cap.read(m) ) {
//
// your image processing here !
//
convert(m); // mat to BufferedImage
repaint();
} else break;
try {
Thread.sleep(50);
} catch (InterruptedException e){}
}
}
public void convert(Mat m)
{
Mat m2 = new Mat();
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
Imgproc.cvtColor(m,m2,Imgproc.COLOR_BGR2RGB);
type = BufferedImage.TYPE_3BYTE_BGR;
}
int blen = m.channels()*m.cols()*m.rows();
if ( b == null || b.length != blen)
b = new byte[blen];
m2.get(0,0,b);
image = new BufferedImage(m.cols(),m.rows(), type);
image.getRaster().setDataElements(0, 0, m.cols(),m.rows(), b);
}
public synchronized void update(Graphics g) {
g.drawImage(image,0,0,this);
}
public static void main( String [] args ) {
pxl win = new pxl();
win.start();
Frame f = new Frame();
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
f.add(win);
f.setSize( 400, 400 );
f.show();
}
}
Thank you my hero.This part it is not working if ( m.channels() > 1 ) { Imgproc.cvtColor(m,m2,Imgproc.COLOR_BGR2RGB); type = BufferedImage.TYPE_3BYTE_BGR; } i do not know why maybe because of the image type->image = new BufferedImage( 800, 600, BufferedImage.TYPE_INT_ARGB);
Asked: 2013-10-26 11:51:42 -0600
Seen: 2,470 times
Last updated: Oct 26 '13