Problems with ofxCv and distance transform

I am having some issues using an image for a distance transform. Following the tutorial here:

http://docs.opencv.org/trunk/d2/dbd/tutorial_distance_transform.html

The only error that I am getting is that cv::cvtColor() is returning errors indicating that the input matrix doesn’t match the conversion type. Otherwise, I’m only getting a black image out of the distance transform, with some occasionally flickering (which really leads me to believe the input to the distance transform is somehow incorrect).

Mat bw, dist; Mat src = toCv(kinect.getDepthPixels()); cv::cvtColor(src, bw, CV_RGBA2GRAY); threshold(src, bw, 40, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); distanceTransform(src, dist, CV_DIST_L2, 3); normalize(dist, dist, 0, 1., NORM_MINMAX); drawMat(dist,0,0,400,300); drawMat(src,400,0,400,300);

So, from what I understand, first I have to get my image into a format suitable for cv, so toCv() seemed to be the first step. Then I need to work on converting that matrix into a binary image. Now the rest is following the tutorial, but when I draw the dist mat, I get nothing, aside from some occasional flickering.

Does anyone know what I might be missing in this? The rest of my ofApp.cpp is below:

http://pastebin.com/JLe7S3MR

Hi there - I stumbled across your question when I was trying to do a similar thing, and I got it working with a few tweaks. The main difference is that I was using an ofImage as the input image, and not a Kinect with the depthPixels buffer.

Here’s my code:

    // convert input rgb ofImage to cv Mat
    Mat inputImage;
    inputImage = toCv(rgbImg.getPixels());
    
    // convert to 8bits gray scale
    inputImage.convertTo(inputImage, CV_8UC3);
    
    // Create binary image from source image
    Mat bw;
    cvtColor(inputImage, bw, COLOR_RGB2GRAY);
    threshold(bw, bw, 0, 255, THRESH_BINARY | THRESH_OTSU);
    
    // Perform the distance transform algorithm
    Mat dist;
    distanceTransform(bw, dist, DIST_L2, 3);
    
    // Normalize the distance image for range = {0.0, 1.0}
    normalize(dist, dist, 0, 1.0, NORM_MINMAX);
    
    // convert distance mat to ofImage
    ofImage finalImage;
    ofPixels finalPixels;
    copy(dist, finalPixels);
    finalImage.setFromPixels(finalPixels);
    finalImage.update();
    
    return finalImage;

The major breakthrough for me was in converting the Mat back to an ofImage. I was using toOf as the conversion function and then I switched to using copy instead. That made the number of input/output channels line up correctly. I didn’t dive in to the toOf function, but my guess is that something in there isn’t working well with binary cv mats.