天天看点

java mat输出图片,用Java将BufferedImage转换为Mat(OpenCV)

java mat输出图片,用Java将BufferedImage转换为Mat(OpenCV)

I've tried this link and have the code below. My program imports images in a BufferedImage format and then displays it to the users. I'm using the matchingTemplate function in OpenCV which requires me to convert it to a Mat format.

The code works if I import the image -> convert it to Mat then save the image using imwrite. The program also allows the user to crop an image and then use the Template matching to compare it to another image. The issue come when I tried to convert the cropped image to Mat I need to convert it from Int to Byte using this code:

im = new BufferedImage(im.getWidth(), im.getHeight(),BufferedImage.TYPE_3BYTE_BGR);

This however results in a black image. But if I get rid of it it only works with imported images and not cropped. What is going on here? I'm certain it is something to do with the coversion process as I have tested the template matching function using read in images.

// Convert image to Mat

public Mat matify(BufferedImage im) {

// Convert INT to BYTE

//im = new BufferedImage(im.getWidth(), im.getHeight(),BufferedImage.TYPE_3BYTE_BGR);

// Convert bufferedimage to byte array

byte[] pixels = ((DataBufferByte) im.getRaster().getDataBuffer())

.getData();

// Create a Matrix the same size of image

Mat image = new Mat(im.getHeight(), im.getWidth(), CvType.CV_8UC3);

// Fill Matrix with image values

image.put(0, 0, pixels);

return image;

}

解决方案

You can try this method, to actually convert the image to TYPE_3BYTE_BGR (your code simply created a blank image of the same size, that is why it was all black).

Usage:

// Convert any type of image to 3BYTE_BGR

im = toBufferedImageOfType(im, BufferedImage.TYPE_3BYTE_BGR);

// Access pixels as in original code

And the conversion method:

public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {

if (original == null) {

throw new IllegalArgumentException("original == null");

}

// Don't convert if it already has correct type

if (original.getType() == type) {

return original;

}

// Create a buffered image

BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);

// Draw the image onto the new buffer

Graphics2D g = image.createGraphics();

try {

g.setComposite(AlphaComposite.Src);

g.drawImage(original, 0, 0, null);

}

finally {

g.dispose();

}

return image;

}