Created
January 12, 2016 13:37
-
-
Save fernandoc1/c5105070fa6acf2d0128 to your computer and use it in GitHub Desktop.
Display OpenCV image in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.opencv.core.*; | |
import org.opencv.highgui.*; | |
import java.awt.*; | |
import javax.swing.*; | |
import java.awt.image.*; | |
public class DisplayImage | |
{ | |
static | |
{ | |
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); | |
} | |
public static BufferedImage Mat2BufferedImage(Mat m) | |
{ | |
int type = BufferedImage.TYPE_BYTE_GRAY; | |
if (m.channels() > 1) | |
{ | |
type = BufferedImage.TYPE_3BYTE_BGR; | |
} | |
int bufferSize = m.channels()*m.cols()*m.rows(); | |
byte[] b = new byte[bufferSize]; | |
m.get(0, 0, b); // get all the pixels | |
BufferedImage image = new BufferedImage(m.cols(), m.rows(), type); | |
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); | |
System.arraycopy(b, 0, targetPixels, 0, b.length); | |
return image; | |
} | |
public static void displayImage(Image img) | |
{ | |
ImageIcon icon = new ImageIcon(img); | |
JFrame frame = new JFrame(); | |
frame.setLayout(new FlowLayout()); | |
frame.setSize(img.getWidth(null)+50, img.getHeight(null)+50); | |
JLabel lbl = new JLabel(); | |
lbl.setIcon(icon); | |
frame.add(lbl); | |
frame.setVisible(true); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
} | |
public static void main(String[] args) | |
{ | |
System.out.println(args[0]); | |
Mat m = Highgui.imread(args[0]); | |
BufferedImage bi = Mat2BufferedImage(m); | |
displayImage(bi); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all: | |
javac -cp "/usr/share/OpenCV/java/opencv-248.jar" DisplayImage.java | |
run: | |
LD_LIBRARY_PATH=/usr/lib/jni/ java -cp /usr/share/OpenCV/java/opencv-248.jar:. DisplayImage /path/to/image.png |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BufferedImage bi = Mat2BufferedImage(bi);
is not working. Netbeans is marking Mat2BufferedImage as error