OpenCV's Vec3b CV_8UC3

Tweet


When creating Mat matrix, use the followings for data type.

CV_8U 8 bit, unsigned, integer, 1 channel
CV_8UC3 8 bit, unsigned, integer, 3 channels
CV_64F 64 bit, floating point, 1 channel
CV_64FC3 64 bit, floating point, 3 channels

Data type to use "at" function is as follows.

unsigned char 8 bit, unsigned, integer, 1 channel
Vec3b 8 bit, unsigned, integer, 3 channels
double 64 bit, floating point, 1 channel
Vec3d 64 bit, floating point, 3 channels

If Vec3b/Vec3d is used for "at" function, it will be a 3-element value. Each element is indicated as [0], [1], or[2].

Here is an example..

Mat gray = imread("gray.bmp", IMREAD_GRAYSCALE);
Mat grayoutput = Mat::zeros(gray.rows, gray.cols, CV_8U);
for (int y = 0; y < gray.rows; y++) {
    for (int x = 0; x < gray.cols; x++) {
        grayoutput.at<unsigned char>(y, x) = gray.at<unsigned char>(y, x) / 2;
    }
}
imwrite("grayoutput.bmp", grayoutput);

Mat color = imread("color.bmp", IMREAD_COLOR);
Mat coloroutput = Mat::zeros(color.rows, color.cols, CV_8UC3);
for (int y = 0; y < color.rows; y++) {
    for (int x = 0; x < color.cols; x++){
        coloroutput.at<Vec3b>(y, x)[2] = color.at<Vec3b>(y, x)[2] / 2;
        coloroutput.at<Vec3b>(y, x)[1] = color.at<Vec3b>(y, x)[1] / 2;
        coloroutput.at<Vec3b>(y, x)[0] = color.at<Vec3b>(y, x)[0] / 2;
    }
}
imwrite("coloroutput.bmp", coloroutput);

Mat scalar = Mat::zeros(480, 640, CV_64F);
for (int y = 0; y < scalar.rows; y++) {
    for (int x = 0; x < scalar.cols; x++) {
        scalar.at<double>(y, x) = y + x;
    }
}
FILE* fpscalar = fopen("scalar.raw", "wb");
for (int y = 0; y < scalar.rows; y++) {
    for (int x = 0; x < scalar.cols; x++) {
        float val = (float)scalar.at<double>(y, x);
        fwrite((void*)&val, sizeof(float), 1, fpscalar);
    }
}
fclose(fpscalar);
imwrite("scalar.bmp", scalar);

Mat vector = Mat::zeros(480, 640, CV_64FC3);
for (int y = 0; y < vector.rows; y++) {
    for (int x = 0; x < vector.cols; x++) {
        vector.at<Vec3d>(y, x)[0] = x;
        vector.at<Vec3d>(y, x)[1] = y;
        vector.at<Vec3d>(y, x)[2] = vector.rows + vector.cols - x - y;
    }
}
FILE* fpvector = fopen("vector.raw", "wb");
for (int y = 0; y < vector.rows; y++) {
    for (int x = 0; x < vector.cols; x++) {
        float val[3];
        val[0] = (float)vector.at<Vec3d>(y, x)[0];
        val[1] = (float)vector.at<Vec3d>(y, x)[1];
        val[2] = (float)vector.at<Vec3d>(y, x)[2];
        fwrite((void*)val, sizeof(float), 3, fpvector);
    }
}
fclose(fpvector);
imwrite("vector.bmp", vector);


Back