#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<vector>
#include<opencv2/core/core.hpp>
using namespace std;
using namespace cv;
class mat
{
public:
//颜色空间缩减,在实际图像处理中,仅用颜色中具有代表性的很小部分就可以达到预期的效果;
//颜色空间缩减的做法:把0-9范围的像素值取为0;10~19范围的取为1;也就是通过舍掉
//余数的方式得到较少的像素值。
//步骤:
//1、遍历图像的每一个像素;
//2、对像素应用公式:new=10*(old/10);
void range(Mat& dst, int num,uchar *table)
{
//判断是灰度图还是彩色图
int dims = dst.channels();
//遍历图像矩阵
if (dims == 1)
{
for (int j = 0; j < dst.rows; j++)
{
uchar* image = dst.ptr<uchar>(j);
for (int k = 0; k < dst.cols; k++)
{
image[k] = table[image[k]];//图像大时这种方法更好
//或者image[k] = image[k] / num * num;
}
}
}
if (dims == 3)
{
vector<Mat> mv;
split(dst, mv);//分离通道
for (int j = 0; j < dst.rows; j++)
{
uchar* image0 = mv[0].ptr<uchar>(j);
uchar* image1 = mv[1].ptr<uchar>(j);
uchar* image2 = mv[2].ptr<uchar>(j);
for (int k = 0; k < dst.cols; k++)
{
image0[k] = image0[k] / num * num;
image1[k] = image1[k] / num * num;
image2[k] = image2[k] / num * num;
//或者image[k]=table[image[k]]
}
}
merge(mv, dst);
//cout << dst << endl;
}
}
};
int main()
{
Mat temp = imread("D:\\VC\\c++\\opencv源码\\opencv源码\\122.bmp");
Mat src = imread("D:\\VC\\c++\\opencv源码\\opencv源码\\12.bmp",IMREAD_GRAYSCALE);
cout << "temp.size()=" << temp.size() << "\ttemp.channels()=" << temp.channels() << endl;
cout << "result.size()=" << src.size() << "\tresult.channels()=" << src.channels() << endl;
Mat dst = src.clone();
//定义公式
int num = 10;//改变缩减程度
uchar table[256];
for (int i = 0; i < 256; i++)
{
table[i] = num * (i / num);
}
mat p;
p.range(dst,num,table);
imshow("原图", src);
imshow("缩减后的图", dst);
waitKey(0);
system("pause");
return 0;
}