Convert BufferedImage to Mat?

1,013 views
Skip to first unread message

Dinh Thap

unread,
Jun 17, 2016, 6:15:12 AM6/17/16
to javacv
Here I did but not working:
int width = bi.getWidth();
int height = bi.getHeight();
opencv_core.Mat mat = new opencv_core.Mat(new opencv_core.Size(width,height), CV_8UC3);
int[] data = ImageJavaUtils.getRGBPixels(bi);

UByteRawIndexer idx = mat.createIndexer();


for(int i = 0;i<height;i++){
for(int j = 0;j<width;j++){
idx.put(i,j,data[j+i*width]);
}
}

I did use tradition javacv way but in my function of project it does not working, even I must saved the image into HDD after use imread and use toMat below then it works. So I must be 
find out other way to convert same as above but not working. Can you show me where I wrong? 
 
public static opencv_core.Mat toMat(BufferedImage img){
OpenCVFrameConverter.ToIplImage cv = new OpenCVFrameConverter.ToIplImage();
Java2DFrameConverter jcv = new Java2DFrameConverter();
return cv.convertToMat(jcv.convert(img));
}

Samuel Audet

unread,
Jun 18, 2016, 1:55:00 AM6/18/16
to jav...@googlegroups.com
On 06/17/2016 07:15 PM, Dinh Thap wrote:
I did use tradition javacv way but in my function of project it does not working, even I must saved the image into HDD after use imread and use toMat below then it works. So I must be 
find out other way to convert same as above but not working. Can you show me where I wrong? 
 
public static opencv_core.Mat toMat(BufferedImage img){
    OpenCVFrameConverter.ToIplImage cv = new OpenCVFrameConverter.ToIplImage();
    Java2DFrameConverter jcv = new Java2DFrameConverter();
    return cv.convertToMat(jcv.convert(img));
}

When you say "it does not working", what isn't working? What happens?

Message has been deleted

Samuel Audet

unread,
Jun 18, 2016, 7:03:56 AM6/18/16
to jav...@googlegroups.com
And, what happens? What error do you get?

On 06/18/2016 07:57 PM, Dinh Thap wrote:
Here I played with not working:
Object B: BufferedImage bi,....
class A(Object B){
    BufferedImage process = preprocess(B);

Dinh Thap

unread,
Jun 18, 2016, 7:08:59 AM6/18/16
to javacv

Object B: BufferedImage bi,....
class A(Object B){
    BufferedImage process = preprocess(B);
             Mat img = toMat(process)

I get img = null. But I save process into HDD and use imread I get success. 

Dinh Thap

unread,
Jun 18, 2016, 7:21:31 AM6/18/16
to javacv

Samuel Audet

unread,
Jun 18, 2016, 9:02:36 AM6/18/16
to jav...@googlegroups.com
On 06/18/2016 08:08 PM, Dinh Thap wrote:
> I get img = null. But I save process into HDD and use imread I get success.

Have you tried to use OpenCVFrameConverter.ToMat instead of
OpenCVFrameConverter.ToIplImage?

Dinh Thap

unread,
Jun 18, 2016, 10:25:00 AM6/18/16
to javacv
Thank you for your patience. 
Reply all
Reply to author
Forward
0 new messages