OpenCV带掩码的阈值处理

9
我正在尝试使用OpenCV的cv::threshold函数(更具体地说是THRESH_OTSU),只是我想用一个掩膜(任何形状)来进行计算,以便在计算过程中忽略外部(背景)。
图像是单通道的(必须如此),下面的红色只是为了标记图像上的一个多边形示例。
我尝试使用adaptiveThreshold,但是有几个问题使其在我的情况下不适用。 enter image description here

使用阈值创建掩模,然后在白色图像上使用带有否定掩模的copyTo。 - Miki
2
谢谢,但那行不通。大津二值化使用图像平均值和其他一些参数。如果我只是屏蔽并复制它,所有黑色像素仍将用于计算那些参数。 - Jaka Konda
啊,好的,我现在明白你的意思了。 - Miki
1个回答

23

通常,您可以使用cv::threshold简单地计算阈值,然后使用反转的masksrc图像复制到dst中。

// Apply cv::threshold on all image
thresh = cv::threshold(src, dst, thresh, maxval, type);

// Copy original image on inverted mask
src.copyTo(dst, ~mask);

然而,使用THRESH_OTSU时,您还需要仅在掩膜图像上计算阈值。以下代码是thresh.cpp中的static double getThreshVal_Otsu_8u(const Mat& _src)的修改版本:

double otsu_8u_with_mask(const Mat1b src, const Mat1b& mask)
{
    const int N = 256;
    int M = 0;
    int i, j, h[N] = { 0 };
    for (i = 0; i < src.rows; i++)
    {
        const uchar* psrc = src.ptr(i);
        const uchar* pmask = mask.ptr(i);
        for (j = 0; j < src.cols; j++)
        {
            if (pmask[j])
            {
                h[psrc[j]]++;
                ++M;
            }
        }
    }

    double mu = 0, scale = 1. / (M);
    for (i = 0; i < N; i++)
        mu += i*(double)h[i];

    mu *= scale;
    double mu1 = 0, q1 = 0;
    double max_sigma = 0, max_val = 0;

    for (i = 0; i < N; i++)
    {
        double p_i, q2, mu2, sigma;

        p_i = h[i] * scale;
        mu1 *= q1;
        q1 += p_i;
        q2 = 1. - q1;

        if (std::min(q1, q2) < FLT_EPSILON || std::max(q1, q2) > 1. - FLT_EPSILON)
            continue;

        mu1 = (mu1 + i*p_i) / q1;
        mu2 = (mu - q1*mu1) / q2;
        sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2);
        if (sigma > max_sigma)
        {
            max_sigma = sigma;
            max_val = i;
        }
    }
    return max_val;
}

您可以将所有内容包装在一个函数中,这里称为threshold_with_mask,该函数为您包装了所有不同的情况。如果没有掩码或掩码全部是白色,则使用cv::threshold。否则,使用上述其中一种方法。请注意,此包装器仅适用于CV_8UC1图像(为简单起见,如果需要,您可以轻松扩展它以处理其他类型),并接受所有THRESH_XXX组合作为原始cv::threshold

double threshold_with_mask(Mat1b& src, Mat1b& dst, double thresh, double maxval, int type, const Mat1b& mask = Mat1b())
{
    if (mask.empty() || (mask.rows == src.rows && mask.cols == src.cols && countNonZero(mask) == src.rows * src.cols))
    {
        // If empty mask, or all-white mask, use cv::threshold
        thresh = cv::threshold(src, dst, thresh, maxval, type);
    }
    else
    {
        // Use mask
        bool use_otsu = (type & THRESH_OTSU) != 0;
        if (use_otsu)
        {
            // If OTSU, get thresh value on mask only
            thresh = otsu_8u_with_mask(src, mask);
            // Remove THRESH_OTSU from type
            type &= THRESH_MASK;
        }

        // Apply cv::threshold on all image
        thresh = cv::threshold(src, dst, thresh, maxval, type);

        // Copy original image on inverted mask
        src.copyTo(dst, ~mask);
    }
    return thresh;
}

以下是完整的参考代码:

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

// Modified from thresh.cpp
// static double getThreshVal_Otsu_8u(const Mat& _src)

double otsu_8u_with_mask(const Mat1b src, const Mat1b& mask)
{
    const int N = 256;
    int M = 0;
    int i, j, h[N] = { 0 };
    for (i = 0; i < src.rows; i++)
    {
        const uchar* psrc = src.ptr(i);
        const uchar* pmask = mask.ptr(i);
        for (j = 0; j < src.cols; j++)
        {
            if (pmask[j])
            {
                h[psrc[j]]++;
                ++M;
            }
        }
    }

    double mu = 0, scale = 1. / (M);
    for (i = 0; i < N; i++)
        mu += i*(double)h[i];

    mu *= scale;
    double mu1 = 0, q1 = 0;
    double max_sigma = 0, max_val = 0;

    for (i = 0; i < N; i++)
    {
        double p_i, q2, mu2, sigma;

        p_i = h[i] * scale;
        mu1 *= q1;
        q1 += p_i;
        q2 = 1. - q1;

        if (std::min(q1, q2) < FLT_EPSILON || std::max(q1, q2) > 1. - FLT_EPSILON)
            continue;

        mu1 = (mu1 + i*p_i) / q1;
        mu2 = (mu - q1*mu1) / q2;
        sigma = q1*q2*(mu1 - mu2)*(mu1 - mu2);
        if (sigma > max_sigma)
        {
            max_sigma = sigma;
            max_val = i;
        }
    }

    return max_val;
}

double threshold_with_mask(Mat1b& src, Mat1b& dst, double thresh, double maxval, int type, const Mat1b& mask = Mat1b())
{
    if (mask.empty() || (mask.rows == src.rows && mask.cols == src.cols && countNonZero(mask) == src.rows * src.cols))
    {
        // If empty mask, or all-white mask, use cv::threshold
        thresh = cv::threshold(src, dst, thresh, maxval, type);
    }
    else
    {
        // Use mask
        bool use_otsu = (type & THRESH_OTSU) != 0;
        if (use_otsu)
        {
            // If OTSU, get thresh value on mask only
            thresh = otsu_8u_with_mask(src, mask);
            // Remove THRESH_OTSU from type
            type &= THRESH_MASK;
        }

        // Apply cv::threshold on all image
        thresh = cv::threshold(src, dst, thresh, maxval, type);

        // Copy original image on inverted mask
        src.copyTo(dst, ~mask);
    }
    return thresh;
}


int main()
{
    // Load an image
    Mat1b img = imread("D:\\SO\\img\\nice.jpg", IMREAD_GRAYSCALE);

    // Apply OpenCV version
    Mat1b cvth;
    double cvth_value = threshold(img, cvth, 100, 255, THRESH_OTSU);

    // Create a binary mask
    Mat1b mask(img.rows, img.cols, uchar(0));
    rectangle(mask, Rect(100, 100, 200, 200), Scalar(255), CV_FILLED);

    // Apply threshold with a mask
    Mat1b th;
    double th_value = threshold_with_mask(img, th, 100, 255, THRESH_OTSU, mask);

    // Show results
    imshow("cv::threshod", cvth);
    imshow("threshold_with_balue", th);
    waitKey();

    return 0;
}

2
非常感谢您的详细回答。我曾希望有比这更简单的方法,现在我为自己没有自己动手感到难过。 - Jaka Konda
1
如果你想加速代码,可以使用并行for循环,例如:src.forEach<uchar>([&](uchar& pixel, const int po[]) -> void {uchar maskPix = mask.at<uchar>(po[0], po[1]); if (maskPix > 0) {h[pixel]++; ++M; }}); - ejectamenta
使用OpenCv直方图算法(Cv2.CalcHist)而不是自己手动处理,也可以加速。该函数接受掩膜作为输入。 - user2959547
@user2959547 这段代码只是对原始的大津算法进行了一些小修补。如果调用calcHist函数可以加速运行,那么你可能也会在原始代码中找到它。但你可以尝试并评估一下。请告诉我结果 ;) - Miki
我用cv::CalcHist(..)替换了第一个for循环,效果非常好。速度与标准的cv::threshold(..)算法一样快。 - user2959547

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接