有关opencv的学习(3)—图像的减色算法

彩色图像由三通道像素组成,每个通道表示红、绿、蓝三原色中一种颜色的亮度值,每个数值都是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);
    
}
显示结果如下图所示:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章