Part 2 – Making OpenCV project in Cygwin
As explained in Part 1, once you have prepared the environment and installed all the required packages, you are now ready to make your first OpenCV project on Cygwin.
Step 1: Write code
Let this be your first OpenCV Project: Read an Image file, convert it to Grayscale image and show it on screen.
Make a folder ‘test’. Then make a file ‘myproj.cpp’ copy the following code in it and put it under a sub folder ‘src’ (i.e. test/src/myproj.cpp)
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <cstdio>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
char* filename = (argc >= 2 ? argv[1] : (char*)"defaultimg.jpg");
Mat imgInput = imread(filename, 1);
if( imgInput.empty() )
{
cout << "Couldn'g open image " << filename << endl;
cout << "Usage: ./myproj.exe <image_name>\n";
return 0;
}
namedWindow("Input Image",WINDOW_AUTOSIZE);
imshow("Input Image",imgInput);
Mat imgGray;
/* Convert to Grayscale */
cv::cvtColor(imgInput, imgGray, COLOR_BGR2GRAY);
namedWindow("Output Image",WINDOW_AUTOSIZE);
imshow("Output Image",imgGray);
cv::waitKey(0);
return 0;
}
Step 2: Make a ‘CMakeLists.txt’ file
This file is used to generate the ‘make’ file. Make a file named ‘CMakeLists.txt’ in the ‘test’ folder and copy the following code in it.
cmake_minimum_required(VERSION 2.8.4)
PROJECT (myproj)
find_package(OpenCV REQUIRED )
set( NAME_SRC
src/myproj.cpp
)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
add_executable( myproj ${NAME_SRC} ${NAME_HEADERS} )
include_directories(/usr/include /usr/include/opencv2 /usr/include/opencv)
link_directories(/usr/lib ${CMAKE_BINARY_DIR}/bin)
target_link_libraries(myproj opencv_core opencv_highgui opencv_imgproc)
Step 3: Build
Open your Cygwin terminal, and go to the ‘test’ folder you just made. Run the following two commands one by one:
$ cmake . $ make
This will give you an executable myproj.exe in ‘test/bin’ folder.
Step 4: Run
To run the executable we just made, we first need to run XServer using following command on your Cygwin terminal:
$ startxwin
This will start the XServer and an XServer icon will appear in your taskbar

Right Click on this icon and from ‘Applications’ menu, select ‘xterm’. This will start the xterm terminal.
Now in the xterm, cd to the ‘test/bin’ folder and execute your exe file with providing it with an image as an argument. (the image must be present in the ‘test/bin’ folder)
$ ./myproj.exe lena.jpg
This will show the input image as well as the grayscale output image


