Introduction
In this tip, we see how to do the conversion between Mat
and BufferedImage
. Mat
is
a data structure from OpenCV to process image. BufferedImage
is a data structure from Java to store images.
Using the Code
Convert Mat to BufferedImage
Mat
data structure has image data, image type (GRAY, BGR), Height, Width. In mat2Img
,
the following function extracts meta data from Mat
data structure and gets assigned to BufferedImage
.
This way, Mat
is assigned toBufferedImage
.
public static BufferedImage mat2Img(Mat in)
{
BufferedImage out;
byte[] data = new byte[320 * 240 * (int)in.elemSize()];
int type;
in.get(0, 0, data);
if(in.channels() == 1)
type = BufferedImage.TYPE_BYTE_GRAY;
else
type = BufferedImage.TYPE_3BYTE_BGR;
out = new BufferedImage(320, 240, type);
out.getRaster().setDataElements(0, 0, 320, 240, data);
return out;
}
Convert BufferedImage to Mat
img2Mat
function accepts BufferedImage
object
as parameter and returns the Mat
object. Mat
Object
is created with 320 width and 240 height, then extract RGB values from BufferedImage
object and assigned todatabuff
which
is a one dimensional int
array. databuff
is
right shifted to 16 , 8, 0 gets ANDED with 0XFF, then assigned to Mat
object.

public static Mat img2Mat(BufferedImage in)
{
Mat out;
byte[] data;
int r, g, b;
if(in.getType() == BufferedImage.TYPE_INT_RGB)
{
out = new Mat(240, 320, CvType.CV_8UC3);
data = new byte[320 * 240 * (int)out.elemSize()];
int[] dataBuff = in.getRGB(0, 0, 320, 240, null, 0, 320);
for(int i = 0; i < dataBuff.length; i++)
{
data[i*3] = (byte) ((dataBuff[i] >> 16) & 0xFF);
data[i*3 + 1] = (byte) ((dataBuff[i] >> 8) & 0xFF);
data[i*3 + 2] = (byte) ((dataBuff[i] >> 0) & 0xFF);
}
}
else
{
out = new Mat(240, 320, CvType.CV_8UC1);
data = new byte[320 * 240 * (int)out.elemSize()];
int[] dataBuff = in.getRGB(0, 0, 320, 240, null, 0, 320);
for(int i = 0; i < dataBuff.length; i++)
{
r = (byte) ((dataBuff[i] >> 16) & 0xFF);
g = (byte) ((dataBuff[i] >> 8) & 0xFF);
b = (byte) ((dataBuff[i] >> 0) & 0xFF);
data[i] = (byte)((0.21 * r) + (0.71 * g) + (0.07 * b)); //luminosity
}
}
out.put(0, 0, data);
return out;
}
Points of Interest
- Learn how to convert
Mat
toBufferedImage
- Learn how to convert
BufferedImage
toMat