彩色圖像由三通道像素組成,每個通道表示紅、綠、藍三原色中一種顏色的亮度值,每個數值都是8位的無符號字符類型,因此顏色總數
爲256 × 256 × 256,即超過1600萬種顏色。因此,爲了降低分析的複雜性,有時需要減少圖像中顏色的數量。一種實現方法是把RGB空間
細分到大小相等的方塊中。例如,如果把每種顏色數量減少到1/8,那麼顏色總數就變爲32 × 32 × 32。將舊圖像中的每個顏色值劃分到一
個方塊,該方塊的中間值就是新的顏色值;新圖像使用新的顏色值,顏色數就減少了。
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
//減色因子
void colorReduce(Mat image, int div=128)
{
int nl=image.rows;
int nc=image.cols*image.channels();
for(int j=0;j<nl;j++)
{
uchar *data=image.ptr<uchar>(j);
for(int i=0;i<nc;i++)
{
data[i]=data[i]/div*div+div/2;
}
}
}
int main( )
{
Mat image=imread("/Users/zhangxiaoyu/Desktop/lena.jpg");
if(image.empty())
{
cout<<"Error!cannot be read...../n";
return -1;
}
colorReduce(image,128);
namedWindow("colorReduce image");
imshow("colorReduce image", image);
waitKey(0);
}
顯示結果如下圖所示: