簡體   English   中英

將圖像轉換為灰度時,OpenCV中有異常

[英]Have exception in OpenCV when converting an image to grayscale

有奇怪的錯誤。
我嘗試將Image轉換為灰度,然后將該打印結果矩陣轉換為文件,但出現異常:

“ ConsoleApplication1.exe中0x00007FF965E31F28處未處理的異常:Microsoft C ++異常:內存位置0x00000041305AF2A0處的cv :: Exception。

以下代碼如下。
當我犯錯時有人可以說我嗎?

int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    string fname;
    cin >> fname;

    cv::Mat img = readImage(fname);

    cv::Mat grayImg(img.size(), CV_64FC1);
    if (img.channels() == 3)
    {
        cvtColor(img, grayImg, CV_BGR2GRAY);
    }
    else
    {
        img.copyTo(grayImg);
    }
    printImg(grayImg);

    cv::waitKey();
    return 0;
}
void printImg(cv::Mat &img)
{
    cout << "---------//------\n";
    if (img.empty())
    {
        cout << "Empty Image\n";
        return;
    }

    for (int i = 0; i < img.size().height; i++)
    {
        for (int j = 0; j < img.size().width; j++)
        {
            cout << img.at<double>(i, j) << " ";
        }
        cout << endl;
    }
    cout << "---------//------\n";
}

字符串錯誤

cout << img.at<double>(i, j) << " ";

如果發生某些情況,OpenCV函數將引發異常。 如果將代碼放入try-catch塊中,則可以看到它們:

int main() try
{
    // your code here
}
catch(const std::exception& e)
{
    std::cout << e.what() << std::endl;
}

當發生不好的情況時-只需查看終端輸出,您就會了解原因。

更新:收到錯誤消息后-很容易解決。 您期望具有64位double值,但是您的灰度Mat it 8位unsigned char

我建議您在代碼中進行此更改,這應該有所幫助:

cv::Mat grayImg;
if (img.channels() == 3)
    cvtColor(img, grayImg, CV_BGR2GRAY);
else if (img.channels() == 4)
    cvtColor(img, grayImg, CV_BGRA2GRAY);
else grayImg = img;
// here grayImg is 8-bit unsigned char
// change it to doubles:
cv::Mat gray64bit;
grayImg.convertTo(gray64bit, CV_64FC1);
printImg(gray64bit);

我不知道為什么您必須讀取圖像然后將其轉換為灰度,而OpenCV支持在通過枚舉CV_LOAD_IMAGE_GRAYSCALE讀取圖像時將圖像轉換為灰度。

http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread

接下來,您使用的默認讀取將以BGR格式將圖像讀取為CV_8U通道。 您不必分配grayImg,cvtColor會為您完成。

http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

灰色圖像將具有與原始圖像相同的深度和大小。 所以你

cout << img.at<double>(i, j) << " ";

產生錯誤。 它應該是

cout << img.at<uchar>(i, j) << " ";

暫無
暫無

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

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