Go to OpenCV documentation here and follow the steps.
The only change is in Step 2. The cmake command should be modified to suit your needs:
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX= ..
You existing installation should be in
/usr/local, so use a different folder, for example you can create one in your home directory.
Here is how you compile with your new version of OpenCV:
Create a folder for your project. It should have the .cpp file and another file names CMakeLists.txt with the following contents:
CPP = g++
CPPFLAGS = -L</path/to/opencv3.0.0/lib> \
$(CPP) $(CPPFLAGS) $^ -o $@
There are three changes you need to make to this file. In the folder to which you installed OpenCV, there will be two directories by the name 'libs' and 'include'. You should put those in lines 2 and 3 respectively. Then in the second last line, put the name of your cpp file.
To compile your project, in a terminal,
cd to you project folder and type
make. The output binary file will be created in the same folder.
Source - StackOverflow