Search code examples
c++qtimage-processingqt4masking

How do I fix eroded rectangles?


Basically, I have an image like this enter image description here

or one with multiple rectangles within the same image. The rectangles are completely black and white have "dirty" edges and gouges, but it's pretty easy to tell they're rectangles. To be more precise, they are image masks. The white regions are parts of the image which are to be "left alone", but the black parts are to be made bitonal.

My question is, how do I make a nice and crisp rectangle out of this degraded one? I am a Python person, but I have to use Qt and C++ for this task. It would be preferable if no other libraries are used.

Thanks!


Solution

  • If the bounding box that contains all non-black pixels can do what you want, this should do the trick:

    int boundLeft = INT_MAX;
    int boundRight = -1;
    int boundTop = INT_MAX;
    int boundBottom = -1;
    for(int y=0;y<imageHeight;++y) {
        bool hasNonMask = false;
        for(int x=0;x<imageWidth;++x) {
            if(isNotMask(x, y)) {
                hasNonMask = true;
                if(x < boundLeft) boundLeft = x;
                if(x > boundRight) boundRight = x;
            }
        }
        if(hasNonMask) {
            if(y < boundTop) boundTop = y;
            if(y > boundBottom) boundBottom = y
        }
    }
    

    If the result has negative size, then there's no non-mask pixel in the image. The code can be more optimized but I haven't had enough coffee yet. :)