Hi, i need to create a binary matrix (one which elements can only be 1 or 0) in openCV. The nearest that I was getting is creating a matrix which elements are 8-bit values using the CV_8UC1 dataType. There must be another dataType which specifies that the matrix elements are 1 bit values, but I can't find anything.

I looked it up in the OpenCV documentation, and found a section which describes how dataTypes are named, but nothing that I tried worked. Here is a citation form the OpenCV documentation about dataTyps:

Template “trait” class for OpenCV primitive data types. A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed short, int, float, double, or a tuple of values of one of these types, where all the values in the tuple have the same type. Any primitive type from the list can be defined by an identifier in the form CV_<bit-depth>{U|S|F}C(<number_of_channels>), for example: uchar ~ CV_8UC1, 3-element floating-point tuple ~ CV_32FC3, and so on.

In summary, how to create a Matrix in openCV which element size is 1 bit?

6 Years
Discussion Span
Last Post by vijayan121

The smallest unit of storage in a computer is one byte. What you want to do is to bitmap the byte(s) of memory, one byte normally holds 8 bits (but may vary depending on the operating system). So if you want an 8x8 matrix of bit then use an array of 8 unsigned char, e.g. unsigned char bits[8], then you can use shift operator and/or the & and | operators to set/clear specific bits.

Another way to do it is to define a structure that contains the bits

struct bits
   unsigned char b1:1; // bit 0
   unsigned char b2:2; // bit 1
   // etc for 8 bits

 struct bits bitArray[8];

With the above structure you can set/clear bits by using the bit name instead of shifting. Example: bitArray[0].b1 = 1; // set bit 0

Edited by Ancient Dragon


Some other options are,


You could just use OpenCv's Mat class with an OpenCV primitive data type; and then just store 0 or 1 as the values.

cv::Mat matrix4( 100, 60, CV_8U ) ;

Standard C++ library:

    #include <vector>
    #include <bitset>

    // fixed width matrix of bits
    std::vector< std::bitset<100> > matrix(60); // matrix of 1/0 values
    // http://en.cppreference.com/w/cpp/utility/bitset

    // resizeable matrix of bool values
    std::vector< std::vector<bool> > matrix2( 60, std::vector<bool>(100) ) ;


#include <vector>
#include <boost/dynamic_bitset.hpp>

// resizeable matrix of bits
std::vector< boost::dynamic_bitset<> > matrix3( 60, boost::dynamic_bitset<>(100) ) ;
// http://www.boost.org/doc/libs/1_51_0/libs/dynamic_bitset/dynamic_bitset.html 
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.