如何使用OpenCV减少图像中的颜色数量? [英] How to reduce the number of colors in an image with OpenCV?

查看:801
本文介绍了如何使用OpenCV减少图像中的颜色数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组图像文件,我想把它们的颜色数减少到64.我如何使用OpenCV?

I have a set of image files, and I want to reduce the number of colors of them to 64. How can I do this with OpenCV?

我需要这样我可以使用64大小的图像直方图。
我正在实现CBIR技术

I need this so I can work with a 64-sized image histogram. I'm implementing CBIR techniques

我想要的是4位调色板的颜色量化。

What I want is color quantization to a 4-bit palette.

推荐答案

有很多方法可以做到。 jeff7建议的方法是好的,但有一些缺点:

There are many ways to do it. The methods suggested by jeff7 are OK, but some drawbacks are:


  • 方法1有参数N和M,你必须选择,必须将其转换为另一个颜色空间。

  • 方法2的回答可能非常慢,因为您应该计算一个16.7 Milion bins直方图,并按频率排序(获得64个更高的频率值)

我喜欢使用基于最高有效位的算法在RGB颜色中使用它到64色图像。如果你使用C / OpenCV,你可以使用类似下面的函数。

I like to use an algorithm based on the Most Significant Bits to use in a RGB color and convert it to a 64 color image. If you're using C/OpenCV, you can use something like the function below.

如果你使用灰色图像,我建议使用LUT )函数的OpenCV 2.3,因为它更快。有一个关于如何使用LUT来减少颜色数量的教程。请参阅:教程:如何扫描图片,查找表... 但是,如果你使用RGB图像,我发现它更复杂。

If you're working with gray-level images I recommed to use the LUT() function of the OpenCV 2.3, since it is faster. There is a tutorial on how to use LUT to reduce the number of colors. See: Tutorial: How to scan images, lookup tables... However I find it more complicated if you're working with RGB images.

void reduceTo64Colors(IplImage *img, IplImage *img_quant) {
    int i,j;
    int height   = img->height;   
    int width    = img->width;    
    int step     = img->widthStep;

    uchar *data = (uchar *)img->imageData;
    int step2 = img_quant->widthStep;
    uchar *data2 = (uchar *)img_quant->imageData;

    for (i = 0; i < height ; i++)  {
        for (j = 0; j < width; j++)  {

          // operator XXXXXXXX & 11000000 equivalent to  XXXXXXXX AND 11000000 (=192)
          // operator 01000000 >> 2 is a 2-bit shift to the right = 00010000 
          uchar C1 = (data[i*step+j*3+0] & 192)>>2;
          uchar C2 = (data[i*step+j*3+1] & 192)>>4;
          uchar C3 = (data[i*step+j*3+2] & 192)>>6;

          data2[i*step2+j] = C1 | C2 | C3; // merges the 2 MSB of each channel
        }     
    }
}

这篇关于如何使用OpenCV减少图像中的颜色数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆