CentOS 7: Build OpenCV 3.1

 

This article will describe installing OpenCV 3.1 and will use manually installed FFmpeg as a backend.

 

1 Download OpenCV

Download OpenCV and checkout 3.1.0 tag.

sudo yum-builddep -y opencv-devel
git clone https://github.com/Itseez/opencv
cd opencv
git checkout 3.1.0 -b 3.1.0

2 Change CMakefile

Building OpenCV with FFmpeg will cause below error.

[ 24%] Built target pch_Generate_opencv_videoio
Linking CXX shared library ../../lib/libopencv_videoio.so
/usr/bin/ld: /usr/local/include/../lib/libswscale.a(swscale.o):
relocation R_X86_64_PC32 against symbol `ff_M24A' can not be used when
making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status
make[2]: *** [lib/libopencv_videoio.so.3.1.0] Error 1
make[1]: *** [modules/videoio/CMakeFiles/opencv_videoio.dir/all] Error 2
make: *** [all] Error 2

Builing FFmpeg with –enable-pic option and building OpenCV with -fPIC cannot resolve this error. This article will change using FFmpeg static library to using dynamic library at cmake/OpenCVFindLibsVideo.cmake in OpenCV.

$ sed -i -e 's/libavformat\.a/libavformat.so/g' \
      -e 's/libavutil\.a/libavutil.so/g' \
      -e 's/libswscale\.a/libswscale.so/g' \
      -e 's/libavresample\.a/libavresample.so/g' \
      -e 's/libavcodec\.a/libavcodec.so/g' \
      cmake/OpenCVFindLibsVideo.cmake

3 Build OpenCV

Build OpenCV without using gstreamer but with using FFmpeg.

$ cmake -G 'Unix Makefiles' -DWITH_FFMPEG=ON -DWITH_GSTREAMER=OFF \
        -DCMAKE_BUILD_TYPE=RELEASE
$ make && sudo make install

4 Execution result

Trying to create thumbnail from movie with OpenCV python.

#!/usr/bin/env python

import sys

import cv2


def create_thumbnail(movie_name, image_name):
    capture = cv2.VideoCapture(movie_name)
    max_frame = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    half_frame = max_frame // 2
    capture.set(cv2.CAP_PROP_POS_FRAMES, half_frame)
    retval, image = capture.read()
    if not retval:
        return False
    cv2.imwrite(image_name, image)
    return True


if __name__ == '__main__':
    argv = sys.argv
    if len(argv) != 3:
        print('Create thumbnail of movie at half position.')
        print('usage: %s [Input movie] [Output thumbnail]' % argv[0])
        exit(1)
    create_thumbnail(argv[1], argv[2])

PNG file is created from MKV file.

$ PYTHONPATH=/usr/local/lib/python2.7/site-packages \
python create-thumbnail.py input.mkv output.png
$ file output.png
output.png: PNG image data, 640 x 360, 8-bit/color RGB, non-interlaced