Knowing the type of the pattern, COLOR_Bayer<type>2BGR
, you can easily find the color of each pixel checking if the coordinates are odd or even, since the pattern is simply a 2x2 that repeats over the whole image.
The OpenCV patterns are:
COLOR_BayerBG2BGR = 46,
COLOR_BayerGB2BGR = 47,
COLOR_BayerRG2BGR = 48,
COLOR_BayerGR2BGR = 49,
COLOR_BayerBG2RGB = COLOR_BayerRG2BGR,
COLOR_BayerGB2RGB = COLOR_BayerGR2BGR,
COLOR_BayerRG2RGB = COLOR_BayerBG2BGR,
COLOR_BayerGR2RGB = COLOR_BayerGB2BGR,
so you can simply check the first four.
The function
#define BLUE 0
#define GREEN 1
#define RED 2
int getColorFromBayer(int r, int c, int type)
will output the color, given the row r
, the column c
, and the type of the pattern type
.
The following code shows how to recover the color of each pixel, and generates a BGR color image of the Bayer pattern.
#include <opencv2\opencv.hpp>
using namespace cv;
//COLOR_BayerBG2BGR = 46,
//COLOR_BayerGB2BGR = 47,
//COLOR_BayerRG2BGR = 48,
//COLOR_BayerGR2BGR = 49,
//
//COLOR_BayerBG2RGB = COLOR_BayerRG2BGR,
//COLOR_BayerGB2RGB = COLOR_BayerGR2BGR,
//COLOR_BayerRG2RGB = COLOR_BayerBG2BGR,
//COLOR_BayerGR2RGB = COLOR_BayerGB2BGR,
#define BLUE 0
#define GREEN 1
#define RED 2
int getColorFromBayer(int r, int c, int type)
{
static int bg[] = { RED, GREEN, GREEN, BLUE };
static int gb[] = { GREEN, RED, BLUE, GREEN };
static int rg[] = { BLUE, GREEN, GREEN, RED };
static int gr[] = { GREEN, BLUE, RED, GREEN };
int rr = r % 2;
int cc = c % 2;
switch (type)
{
case COLOR_BayerBG2BGR: return bg[2 * rr + cc];
case COLOR_BayerGB2BGR: return gb[2 * rr + cc];
case COLOR_BayerRG2BGR: return rg[2 * rr + cc];
case COLOR_BayerGR2BGR: return gr[2 * rr + cc];
}
return -1;
}
int main()
{
Mat3b bayer(10,10, Vec3b(0,0,0));
// Create bayer pattern BG
for (int r = 0; r < bayer.rows; ++r)
{
for (int c = 0; c < bayer.cols; ++c)
{
int color = getColorFromBayer(r,c,COLOR_BayerBG2BGR);
switch (color)
{
case BLUE : bayer(r, c) = Vec3b(255, 0, 0); break;
case GREEN: bayer(r, c) = Vec3b(0, 255, 0); break;
case RED : bayer(r, c) = Vec3b(0, 0, 255); break;
}
}
}
return 0;
}