Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to read and display image in OpenCV

📅 2014-Feb-11 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ iplimage, mat, opencv ⬩ 📚 Archive

OpenCV can be used to easily read an image file and display it in a window. The core and highgui modules are needed to achieve this. The image is read into a cv::Mat object. cv::Mat is the modern replacement for the old IplImage object, which came from Intel.

#include <opencv2/highgui.hpp>

// Read image from file
cv::Mat img = cv::imread("foobar.jpg");

// Create a window
cv::namedWindow("foobar");

// Display image in window
cv::imshow("foobar", img);

// Wait for user to press a key in window
cv::waitKey(0);

To be able to compile this code, link with the core and highgui modules using -lopencv_core -lopencv_highgui.

The legacy method to achieve the same using IplImage is:

#include <opencv2/opencv.hpp>

// Read image from file
IplImage* img = cvLoadImage("foobar.jpg");

// Display image in window
cvLoadImage("foobar", img);

// Wait for user to press a key in window
cvWaitKey(0);

Tried with: Ubuntu 12.04 LTS


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧