使用 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 显示图像。