My goal is to drawing a cv::Mat using ofImage

Hi, All.

I met this strange result when run this code.
My goal is to drawing a cv::Mat using ofImage.

ofImage aa;
void ofApp::setup(){
    cv::Mat data = cv::Mat(52, 52, CV_8UC3);
    //change some pixel value
    for(int j=0;j<52;j++) {
      for (int i=0;i<52;i++) {
<Vec3b>(j, i)[0] = 0;
<Vec3b>(j, i)[1] = 255;
<Vec3b>(j, i)[2] = 0;
    toOf(data, aa);
void ofApp::draw(){
    ofSetColor(255, 255, 255);
    aa.draw(0, 0, 512, 512);

My strange result is …

What’s wrong to me ?



You need to update the image after toCv():

toOf(data, aa);

An ofImage usually hold the pixels (ofPixels) in the CPU RAM and a corresponding texture (ofTexture) in the graphics card RAM. When you change the ofPixels directly you have to update the ofTexture to make it reflect the change. This is where the ofImage update() method is useful.
toOf() copy only the pixels, this is why you need the aa.update() before you can draw it.

Also, you don’t need the aa.setImageType(OF_IMAGE_COLOR) because toOf() properly setup the ofImage.

[edit] In fact, do not set the image type or you get this error:

[ error ] ofImage: getBmpFromPixels(): unable to get FIBITMAP from ofPixels
[ error ] ofImage: putBmpIntoPixels(): unable to set ofPixels from FIBITMAP
1 Like

Thanks, Lilive.

It works ~