使用opencv和LUT减少颜色深度

时间:2013-02-11 12:55:13

标签: c++ opencv colors depth

我想通过颜色深度缩放来执行色彩还原。

喜欢这个例子: enter image description here

第一张图片是CGA分辨率,第二张是EGA,第三张是HAM。 我想用cv :: LUT来做,因为我认为这样做更好。 我可以使用以下代码处理灰度:

Mat img = imread("test1.jpg", 0);
uchar* p;
Mat lookUpTable(1, 256, CV_8U);
p = lookUpTable.data;
for( int i = 0; i < 256; ++i)
    p[i] = 16 * (i/16)
LUT(img, lookUpTable, reduced);

原:enter image description here

颜色减少:enter image description here

但是如果我尝试用颜色做的话我会得到奇怪的结果..

enter image description here

使用此代码:

imgColor = imread("test1.jpg");
Mat reducedColor;
int n = 16;
for (int i=0; i<256; i++) {
    uchar value = floor(i/n) * n;
    cout << (int)value << endl;
    lut.at<Vec3b>(i)[2]= (value >> 16) & 0xff;
    lut.at<Vec3b>(i)[1]= (value >> 8) & 0xff;
    lut.at<Vec3b>(i)[0]= value & 0xff;
} 
LUT(imgColor, lut, reducedColor);

2 个答案:

答案 0 :(得分:3)

你现在可能已经开始了,但问题的根源在于你正在向uchar value进行16位移位,这只是8位长。在这种情况下,即使是8位移位也是如此,因为您将擦除uchar中的所有位。然后有一个事实是cv::LUT documentation明确指出src必须是“8位元素的输入数组”,这在你的代码中显然不是这样。最终结果是只有彩色图像的第一个通道(蓝色通道)被cv::LUT转换。

解决这些限制的最佳方法是跨通道分割彩色图像,分别转换每个通道,然后将转换后的通道合并为新的彩色图像。请参阅以下代码:

/*
Calculates a table of 256 assignments with the given number of distinct values.

Values are taken at equal intervals from the ranges [0, 128) and [128, 256),
such that both 0 and 255 are always included in the range.
*/
cv::Mat lookupTable(int levels) {
    int factor = 256 / levels;
    cv::Mat table(1, 256, CV_8U);
    uchar *p = table.data;

    for(int i = 0; i < 128; ++i) {
        p[i] = factor * (i / factor);
    }

    for(int i = 128; i < 256; ++i) {
        p[i] = factor * (1 + (i / factor)) - 1;
    }

    return table;
}

/*
Truncates channel levels in the given image to the given number of
equally-spaced values.

Arguments:

image
    Input multi-channel image. The specific color space is not
    important, as long as all channels are encoded from 0 to 255.

levels
    The number of distinct values for the channels of the output
    image. Output values are drawn from the range [0, 255] from
    the extremes inwards, resulting in a nearly equally-spaced scale
    where the smallest and largest values are always 0 and 255.

Returns:

Multi-channel images with values truncated to the specified number of
distinct levels.
*/
cv::Mat colorReduce(const cv::Mat &image, int levels) {
    cv::Mat table = lookupTable(levels);

    std::vector<cv::Mat> c;
    cv::split(image, c);
    for (std::vector<cv::Mat>::iterator i = c.begin(), n = c.end(); i != n; ++i) {
        cv::Mat &channel = *i;
        cv::LUT(channel.clone(), table, channel);
    }

    cv::Mat reduced;
    cv::merge(c, reduced);
    return reduced;
}

答案 1 :(得分:0)

in都是整数,因此i/n是整数。也许您希望在发言之前将其转换为加倍((double)i/n)并乘以n