簡體   English   中英

Opencv斷言失敗

[英]Opencv assertion failed

我試圖從圖像中僅提取具有特定大小的輪廓。

我是這樣處理的

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 錯誤:斷言失敗

這是給我錯誤的圖像示例。

你必須小心這一點:

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

如果寬度是圖像寬度,則此處超出范圍。 您要么必須從寬度中減去 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM