Google Code Prettify

2013年3月18日 星期一

OpenCV 顯示影像(Display Image)

環境設定請參考:Visual Studio 2012 安裝 OpenCV 2.4.3

 範例程式:C:\OpenCV2.4\samples\cpp\tutorial_code\introduction\display_image\display_image.cpp (內文的程式碼有稍作修改)



#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    Mat image;
    if( argc != 2)
    {
        cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
        image = imread("lena.jpg", CV_LOAD_IMAGE_COLOR); // Read the file
    }
    else
    {
        image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file
    }

    if(! image.data ) // Check for invalid input
    {
        cout << "Could not open or find the image" << endl;
        system("pause");
        return -1;
    }

    namedWindow( "Lena - Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
    imshow( "Lena - Display window", image ); // Show our image inside it.

    waitKey(0); // Wait for a keystroke in the window
    return 0;
}
imread(const string& filename, int flags=1)
  • filename – Name of file to be loaded.
  • flags – Flags specifying the color type of a loaded image:
    >0 Return a 3-channel color image
    =0 Return a grayscale image
    <0 Return the loaded image as is.
支援圖檔型態:
  • Windows bitmaps - *.bmp, *.dib (always supported)
  • JPEG files - *.jpeg, *.jpg, *.jpe (see the Notes section)
  • JPEG 2000 files - *.jp2 (see the Notes section)
  • Portable Network Graphics - *.png (see the Notes section)
  • Portable image format - *.pbm, *.pgm, *.ppm (always supported)
  • Sun rasters - *.sr, *.ras (always supported)
  • TIFF files - *.tiff, *.tif (see the Notes section)
 namedWindowimshow的第一個參數(視窗名稱)要設定一樣,否則執行後會跳出兩個視窗。  將欲讀取的影像檔放在與執行檔同一個資料夾,否則必須自訂path。 然後問題來了。
如果用的是Visual Studio 2012的話,它會跳出以下訊息:
google查詢之後發現原因如下: Visual Studio 2012 is distributed with msvcp110d.dll. msvcp110d.dll is a newer version of MSVCP100D.DLL. It seems that OpenCV is using MSVCP100D.DLL which is not provided with Visual Studio 2012. 簡單來說就是Visual Studio 2012用的是較新的msvcp110d.dll跟msvcr110d.dll,而OpenCV 2.4.3用的是msvcp100d.dll跟msvcr100d.dll,才會發生這個錯誤。 欲修正此錯誤,請下載msvcp100d.dllmsvcr100d.dll 將這兩個檔案複製到 C:\Windows\System32 資料夾下, 若是Windows 7 64bit使用者則再複製到 C:\Windows\SysWOW64 資料夾下。 成功執行之後的結果如下:
以下是比較簡單的範例,實作讀取圖片並儲存。
int main()
{
    IplImage *InImage;
 
    InImage = cvLoadImage("lena.jpg",-1);
    CvSize Size1 = cvGetSize(InImage);
 
    //建立視窗(視窗名稱,參數)
    cvNamedWindow("InImage",1);
 
    //顯示影像(視窗名稱,影像檔案)
    cvShowImage("InImage",InImage);
 
    cvWaitKey(0); //按下任意按鍵可將圖片關閉
 
    //儲存影像(欲儲存名稱, 影像檔案)
    cvSaveImage("saved.jpg", InImage);
 
    return 0;
}

沒有留言:

張貼留言