OpenCV on Arch Linux

Computer vision seems to be an interesting field to explore in. This is a simple tutorial on how to get OpenCV up and running on Arch Linux. A short C++ program is provided to confirm that OpenCV was successfully installed and compilation with OpenCV libraries actually works.

To keep it simple, the provided code is quite minimal and will only load a picture, convert it to grayscale and then display both pictures in two separate windows.

Install

The first thing you want to do is install all build-time dependencies as well as OpenCV itself.

pacman -Syu base-devel opencv opencv-samples

After this, it is a good idea to check if opencv was successfully installed by checking the libraries available for it via pkg-config --libs opencv

If the output lists a bunch of libraries, that’s good! If the command outputs something similar to the block below, then something definitely went wrong.

Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing 'opencv.pc'
to the PKG_CONFIG_PATH environment variable
No package 'opencv' found

Code

#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
	Mat sourceImage = imread("res/7914426490_bf708f9887_z.jpg");

	// Check if image was successfully read
	if(sourceImage.empty())
	{
		cerr << "Could not read image" << endl;
		return 1;
	}

	// Display source image
	namedWindow("Source", WINDOW_AUTOSIZE);
	imshow("Source", sourceImage);

	// Convert to grayscale
	Mat grayImage;
	cvtColor(sourceImage, grayImage, COLOR_BGR2GRAY);

	// Display gray image
	namedWindow("Grayscale", WINDOW_AUTOSIZE);
	imshow("Grayscale", grayImage);

	//Wait until any key is pressed
	waitKey(0);

	cout << "Closing ..." << endl;

	return 0;
}

Compiling & Running

Two ways to compile and run the code, the quickest way is definitely the first.

Using git & make

git clone https://github.com/grawlinson/opencv-grayscale && cd opencv-grayscale
make
./opencv-grayscale

Using the command line

Copy & paste the code into src/opencv-grayscale.cpp and save the image in a folder called res. The folder should look like the following:

.
+-- res
│   \-- 7914426490_bf708f9887_z.jpg
\-- src
   \-- opencv-grayscale.cpp

To compile using g++ (installed with pacman earlier in the base-devel package), insert the following code in a terminal of your choosing.

Note: You may have to remove the backslashes and type it all on one line.

g++ src/opencv-grayscale.cpp -o opencv-grayscale \
	-I /usr/include/opencv \
	-L /usr/lib \
	-lopencv_core \
	-lopencv_imgproc\
	-lopencv_highgui\
	-lopencv_imgcodecs

Then run the program ./opencv-grayscale to see the original & grayscale images.

Results

Original image

Grayscale image

External Resources