简体   繁体   English

如何在OpenCV中遮罩浮点图像?

[英]How to mask a floating-point image in OpenCV?

I have a Nx1 matrix of floating-point values. 我有一个Nx1浮点值矩阵。 I wish to get the average of only those values starting from the 22nd to the Nth item. 我希望仅获取从第22nd到第Nth项的值的平均值。 I have created a binary mask of Nx1 dimensions, put 0s in the range [0,21] and 1s in the rest. 我创建了一个Nx1尺寸的二进制掩码,将0s[0,21] ,其余设置为1s Applying that mask while calculating the average (using inbuilt functions for maximum speed) gives an error. 在计算平均值时应用该蒙版(使用内置函数获得最大速度)会产生错误。 The code snippet is given below. 代码段如下所示。

The error is: 错误是:

sizes on input arguments do not match in cvSvg()" 输入参数的大小在cvSvg()中不匹配”

What should be the correct mask? 正确的口罩应该是什么? I have tried using floating-points instead of integers in the mask, still not working. 我尝试在掩码中使用浮点而不是整数,但仍然无法正常工作。

CvMat mask;
int i;
int N = img->width;
IplImage* W = cvCreateImage( cvSize(N, 1), IPL_DEPTH_32F , 1 );
IplImage* A = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F , 1 );
cvConvertScale(img, A);
int* vals = (int*)malloc(N*sizeof(int));

for(i=0; i<N; i++)
{
    if(i<22)
        vals[i] = 0;
    else
        vals[i] = 1;
}
cvInitMatHeader(&mask, N, 1, CV_8U, vals);

cvSVD(A, W, NULL, NULL, CV_SVD_MODIFY_A);

CvScalar mean = cvAvg(W, &mask);

Here is how I computed the mask with a contrived example, but it appears to work just fine. 这是我使用人为的示例计算蒙版的方法,但它似乎工作得很好。

int main(int argc, char* argv[])
{
    int N = 50;
    CvMat* a = cvCreateMat(1, N, CV_32FC1);
    CvMat* mask = cvCreateMat(1, N, CV_8UC1);

    float* aData = a->data.fl;
    uchar* maskData = mask->data.ptr;

    for(int i = 0; i < a->cols; i++)
    {
        aData[i] = (float)i;

        if(i < 22)
        {
            maskData[i] = 0;
        }
        else
        {
            maskData[i] = 1;
        }
    }

    CvScalar avg = cvAvg(a);
    cout << "Average without mask: " << avg.val[0] << endl;

    avg = cvAvg(a, mask);
    cout << "Average with mask: " << avg.val[0] << endl;

    cvReleaseMat(&a);
    cvReleaseMat(&mask);
    return 0;
}

This produces the following output: 这将产生以下输出:

Average without mask: 24.5
Average with mask: 35.5

So, it is working for this simple example. 因此,它适用于此简单示例。 Hopefully that will get you going again. 希望这能使您再次尝试。

the image you use as mask does not have to be double, but Uint, the code is fine I think, not really sure about the initialization of the mask. 您用作遮罩的图像不必一定要加倍,但是Uint,我认为代码很好,并不是真的确定遮罩的初始化。 still you must declare W as follow 你仍然必须声明W如下

IplImage* W = cvCreateImage( cvSize(N, 1), IPL_DEPTH_8U, 1 ); IplImage * W = cvCreateImage(cvSize(N,1),IPL_DEPTH_8U,1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM