使用 OpenCV 載入並顯示影象

在這個例子中,我們將看到如何從磁碟載入彩色影象並使用 OpenCV 的內建函式顯示它。我們可以使用 C / C++,Python 或 Java 繫結來完成此任務。

在 C++中:

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

#include <iostream>

using namespace cv;

int main(int argc, char** argv) {
    // We'll start by loading an image from the drive
    Mat image = imread("image.jpg", CV_LOAD_IMAGE_COLOR);

    // We check that our image has been correctly loaded
    if(image.empty()) {
        std::cout << "Error: the image has been incorrectly loaded." << std::endl;
        return 0;
    }

    // Then we create a window to display our image
    namedWindow("My first OpenCV window");

    // Finally, we display our image and ask the program to wait for a key to be pressed
    imshow("My first OpenCV window", image);
    waitKey(0);

    return 0;
}

在 Python 中:

import sys
import cv2

# We load the image from disk
img = cv2.imread("image.jpg", cv2.CV_LOAD_IMAGE_COLOR)

# We check that our image has been correctly loaded
if img.size == 0
    sys.exit("Error: the image has not been correctly loaded.")

# We create a window to display our image
cv2.namedwindow("My first OpenCV window")

# We display our image and ask the program to wait until a key is pressed
cv2.imshow("My first OpenCV window", img)
cv2.waitKey(0)

# We close the window
cv2.destroyAllWindows()

在 Java 中:

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.highgui.Highgui;
public class Sample{
public static void main (String[] args) {

    //Load native opencv library
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    //Read image from file first param:file location ,second param:color space
    Mat img = imread("image.jpg",CV_LOAD_IMAGE_COLOR);

    //If the image is successfully read.
    if (img.size() == 0) {
        System.exit(1);
    }
}

HighGui 在 opencv java 中沒有 namedwindows 或 imshow 等價物。使用 swing 或 swt 顯示影象。