Opencv断言失败了

时间:2014-09-17 10:04:18

标签: c++ opencv image-processing

我试图仅从图像中提取具有特定大小的轮廓。

我像这样处理

int offsetX ;
int offsetY ;
//here: read original image as 8UC3 
cv::Mat original = cv::imread("0.png");
Mat imgx=original.clone();
cv::imshow("original", original);
cvtColor(imgx,imgx,CV_BGR2GRAY);
Mat thresh;
vector<Vec4i> hierarchy;
RNG rng(12345);
vector < vector<Point> > contours; 
adaptiveThreshold(imgx, thresh, 255, 1, 1, 31, 2);
findContours(thresh, contours, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat drawing = Mat::zeros(thresh.size(), CV_8UC3);
cout << "drawing "<<drawing.type()<<endl;
cv::Mat image = cv::Mat(original.rows, original.cols, original.type());
image.setTo(cv::Scalar::all(255));
for (size_t i = 0; i < contours.size(); i++)
{
    vector < Point > cnt = contours[i];
    if (contourArea(cnt) > 0)
    {
        Rect rec = boundingRect(cnt);
        if ((rec.height > 20 ) &&(3.5*rec.height>rec.width)&&  (rec.width>15)/*&& (rec.width<40)*/)
        {
            cout<<rec.x<<" "<<rec.y<<endl;
            offsetX=rec.x;
            offsetY=rec.y;
            Mat roi = original(rec);
            int width = roi.cols;
            int height = roi.rows;
            cout <<"h= "<<height<<" w= "<<width<<endl;
            cv::Rect characterLocation;
            if(height>35)
                characterLocation = cv::Rect(offsetX+3, offsetY, width, height);
            else
                characterLocation = cv::Rect(offsetX, offsetY, width, height);
            original(characterLocation).copyTo(image(characterLocation));
            imshow("jihedddd",roi); 
            imwrite("xxxxxx.png",roi);
            Mat stagedImage;
            Mat img;
            Scalar color = Scalar(255, 255, 255);
            drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
            imshow("Contours", drawing);
            waitKey();
            GaussianBlur(stagedImage, img, Size(5, 5), 2, 2);
            medianBlur(img, stagedImage, 3);
            Mat copy = original.clone();
            rectangle(copy, Point(rec.x, rec.y),
            Point(rec.x + rec.width, rec.y + rec.height),
            CV_RGB(0x00,0x00,0xff), 3);
            cv::imshow("char copied", image);
        }
    }
}
medianBlur(image,image,3);
cv::imshow("char copied", image);
cv::imwrite("characterC_result.tiff ", image);
cv::waitKey();

但是当我运行此代码时出现错误

    opencv  error :assertion failed

这是image的示例,它给出了下面的错误。 请帮忙。

1 个答案:

答案 0 :(得分:1)

你必须小心这个:

characterLocation = cv::Rect(offsetX+3, offsetY, width, height);

如果width是图像宽度,那么你在这里是不可能的。你要么必须从宽度减去x,要么将矩形裁剪到图像边界:

// get the Rect for the original image:
cv::Rect borders(Point(0,0), image.size());

// crop to the legal size:
characterLocation = cv::Rect(offsetX+3, offsetY, width, height) & borders;