在此示例中,我们将看到如何从磁盘加载彩色图像并使用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) { // 我们将从加载驱动器中的图像开始 Mat image = imread("image.jpg", CV_LOAD_IMAGE_COLOR); // 我们检查图像是否已正确加载 if(image.empty()) { std::cout << "Error: the image has been incorrectly loaded." << std::endl; return 0; } // 然后我们创建一个窗口来显示我们的图像 namedWindow("My first OpenCV window"); // 最后,我们显示图像并要求程序等待按键被按下 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 ifimg.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) { //加载本机opencv库 System.loadLibrary(Core.NATIVE_LIBRARY_NAME); //从文件的第一个参数:文件位置读取图像,第二个参数:颜色空间 Mat img = imread("image.jpg",CV_LOAD_IMAGE_COLOR); //如果图像读取成功。 if (img.size() == 0) { System.exit(1); } }
HighGui在opencv java中没有namedwindows或imshow等效项。使用swing或swt显示图像。