Skip to content

wagavulin/opencvr

Repository files navigation

opencvr: Ruby binding of OpenCV

About this library

opencvr is a ruby extension library which provides the wrapper of OpenCV.

Tiny sample

#!/usr/bin/env ruby

$:.unshift __dir__ + "/.."
require 'numo/narray'
require 'cv2'

# Create 3 channels color (BGR) image buffer (width: 600, height: 400)
img = Numo::UInt8.zeros(400, 600, 3)
# draw a circle of radius: 100 at position (200, 200) with blue color
# (BGR: 255, 0, 0), thickness: 3 and antialiased
CV2::circle(img, [200, 200], 50, [255, 0, 0], thickness: 3, lineType: CV2::LINE_AA)
# Save the image to out.jpg
CV2::imwrite("out.jpg", img)

The above sample assumes that cv2.so is located in the parent folder. Modify $: (library path) in the 3rd line according to your environment.

How to create binding code

opencvr generates binding code with the similar way of python binding, which is officially provided by OpenCV.

To provide ruby API of C/C++ library, we need to write binding code for each API (functions, enums, etc.). OpenCV has many APIs, so it would be an exhausting task if we manually write all binding codes.

To avoid this problem, python binding codes are automatically generated by reading header files of C++ interface. opencvr uses similar way and reuse some scripts of python binding generator.

Supported features

List of supported functions are listed in autogen/support-status.csv (auto-generated by gen2rb.py).

cv::Mat and Numo::NArray

cv::Mat is the matrix class used in OpenCV, but in python binding ndarray of Numpy is used, which is widely used in python world. It enables easily combining other libraries, such as data science and machine learning libraries.

In opencvr, Numo::NArray is used as matrix library because it's widely used in ruby world.

How to install

From gem

opencvr gem has not been created yet.

Build from source

Prerequisites

Below components are required to build opencvr:

  • Ruby (>3.0.0)
    • recommend to use rbenv
  • Python (>3.x)
  • OpenCV
    • libopencv-dev (apt package on Ubuntu-22.04)
    • opencv (brew package on macOS)

Build

$ make -C dummycv  # Generate dummycv/libdummycv.so
$ mv dummycv/libdummycv.so . # This step is required only on macOS
$ ./dev-tools/gen-headers-txt.rb > headers.txt
$ ./gen2rb.py      # Generate files under autogen/
$ ruby extconf.rb  # Generate Makefile
$ make             # Generate cv2.so

Run test

$ ./test/bind-test1.rb

License

Apache License 2.0. See License.txt.

gen2rb.py and hdr_parser.py are created by using files in OpenCV, which is under Apache Licsense Version 2.0. Refer the original file.