为什么我不能在我的函数中访问Object?

时间:2014-07-20 14:09:45

标签: c++ opencv

我有一个功能可以检测两帧之间的运动,并在变量 cv :: Mat result_cropped 中存储仅移动对象的裁剪图像。现在我想添加一个函数来检查result_cropped是否有黑色像素。我轻松地编写了代码,但我完全坚持尝试在我的课程中实现它。

由于某些原因,我的blackDetection(Mat& cropped)无法访问裁剪的图像,导致程序崩溃。 继承了我的简化代码:

void ActualRec::run(){

    while (isActive){

    //...code to check for motion
    //if there was motion a cropped image will be stored in result_cropped      
        number_of_changes = detectMotion(motion, result, result_cropped, region,  max_deviation, color);

        if(number_of_changes>=there_is_motion) {
            if(number_of_sequence>0){
            // there was motion detected, store cropped image - this works 
            saveImg(pathnameThresh, result_cropped);

                if (blackDetection(result_cropped)==true){
                    //the cropped image has black pixels
                }
                else {
                   //the cropped image has no black pixels

            }
            number_of_sequence++;
        }
        else
        {
            // no motion was detected
        }
    }
}

bool ActualRec::blackDetection(Mat & result_cropped){
//...check for black pixels, program crashes since result_cropped is empty
//if i add imshow("test",result_cropped) I keep getting an empty window
   if (blackPixelCounter>0){
       return true;
   }
else return false;
}

同样,问题是我无法在blackDetection中访问result_cropped(Mat& result_cropped)。

\\ edit:我的完整代码http://pastebin.com/3i0WdLG0。请有人帮助我。这个问题对我没有任何意义..

1 个答案:

答案 0 :(得分:1)

cv::waitKey()中没有blackDetection(),因此在到达cvWaitKey()中的run()之前,您将崩溃。你得出结论result_cropped是"空"。

您尚未在任何地方分配croppedBlack,因此您将在croppedBlack.at<Vec3b>(y,x)[c] =上崩溃。

blackDetection()开头添加此内容(例如):

croppedBlack.create(result_cropped.size(), result_cropped.type());

为了加快速度,请参阅How to scan images ... with OpenCV : The efficient way

bool ActualRec::blackDetection(Mat& result_cropped)
{
    croppedBlack.create(result_cropped.size(), result_cropped.type());

    int blackCounter = 0;
    for(int y = 0; y < result_cropped.rows; ++y)
    {
        Vec3b* croppedBlack_row = croppedBlack.ptr<Vec3b>(y);
        Vec3b* result_cropped_row = result_cropped.ptr<Vec3b>(y);

        for(int x = 0; x < result_cropped.cols; ++x)
        {
            for(int c = 0; c < 3; ++c)
            {
               croppedBlack_row[x][c] = 
                    saturate_cast<uchar>(alpha * result_cropped_row[x][c] + beta);
            }
        }
    }
}