Create a single colored blank image in C++ using OpenCV
We are going to see how to create an image and assign it any single color value in C++ using OpenCV.
OpenCV is an open-source C++ library for Image processing and computer vision.
Prerequisite: single-colored blank image in C++ with OpenCV
- OpenCV installed on your system. (Install OpenCV C++ with Visual Studio)
- How to compile and run the program of OpenCV.
If you have not set up the environment in Visual Studio and want to manually compile the code in terminal follow the steps below:
You can compile the code using the following command in the terminal (don’t include parenthesis):
g++ -o (outputFileName) (fileName).cpp `pkg-config --cflags --libs opencv`
(Don’t confuse between ‘ and ` in above command use `
After executing the above command a file will be created with the name you specified:
./(outputFileName)
Full Code:
//author @Nishant #include<opencv2/highgui/highgui.hpp> #include<iostream> using namespace std; using namespace cv; int main(){ // To create a 3 channel, 8 bit image // You can change it CV8UC1/2/3/4/(n) // Specify height as 300 and width as 500 // Scalar function is used to set the color value for // BGR set the values of your wish // I'm going to set it to color Blue Mat img(300, 500, CV_8UC3, Scalar(255, 0, 0)); // Verify if image is created or not if(img.empty()){ cout << "Could not load image" << endl; cin.get(); return -1; } string windowName = "Blank Image"; // Name of output windows // CV_WINDOW_AUTOSIZE : the user cannot resize the // window, the size is constrainted by the image displayed. namedWindow(windowName, CV_WINDOW_AUTOSIZE); // to show the window to the window specified by the name // It is better to use an extra string variable to // avoid any mistake // otherwise new window will be created automatically // by imshow() function imshow(windowName, img); // wait for any keypress waitKey(0); // Following function can be used to destroy all the // windows on screen // alternatively you can use destroyWindow(windowName) // to destroy only specify window destroyAllWindows(); return 0; }
Output
I have compiled in VS Code in Ubuntu using terminal and my file name is BlankImage.cpp.
Leave a Reply