With this example, we will see how to load a color image from disk and display it using OpenCV's built-in functions. We can use the C/C++, Python or Java bindings to accomplish this.
In 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;
}
In 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()
In 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 has no namedwindows or imshow equivalents in opencv java. Use swing or swt to display image.