(数组,将读取的24位真彩色图像数据进行处理转换成灰度图)
在自然界中,颜色本身非常容易受到光照的影响,RGB变化很大。因此,在进行图像处理之前,至关重要的一步就是将图像转化为灰度图。对于彩色转灰度,共有三种方式式:Gray = R0.299 + G0.587 + B0.114(加权法),Gray = (R+G+B)/3(平均值法),Gray=max(R,G,B)(即找出三者的最大值)。对于一张图像,我们会得到3个N行M列的矩阵分别表示R、G、B的像素值(RGB对应的范围均为0~255),我们需要将相应的每一对像素值代入以上公式,计算出相应的灰度值。现给出一幅图像R、G、B的像素值,请计算出它的灰度图。
输入格式:
每个输入包含一个测试用例,第一行输入正整数N(N<100)和M(M<100)和type(分别用0,1,2表示,0表示加权法,1表示平均值法,2表示最大值法),中间以空格隔开。接下来3N行依次输入R的像素值矩阵、G的像素值矩阵、B的像素值矩阵。每个像素值间以空格隔开,每两个矩阵无间隔(RGB取值均为0~255)。
输出格式:
在N行M列中输出计算得到的灰度图像素值。像素值间以空格隔开,末尾无多余空格。
输入样例:
3 3 0
3 6 8
4 8 6
3 9 5
1 4 8
5 2 8
2 5 9
2 5 7
7 5 2
3 9 6
输出样例:
1 4 7
4 4 6
2 6 7
题解:
#include<iostream>
#include<vector>
#include<iomanip>
using namespace std;
vector<vector<int>> WeightedToG(vector<vector<int>>& R,vector<vector<int>>& G,vector<vector<int>>& B,int n,int m)
{ //加权处理方法
int avg = 0;
vector<vector<int>> result(n,vector<int>(m));
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
avg = R[i][j]*0.299+G[i][j]*0.587+B[i][j]*0.114;
result[i][j] = avg;
}
}
return result;
}
vector<vector<int>> AvgToG(vector<vector<int>>& R,vector<vector<int>>& G,vector<vector<int>>& B,int n,int m)
{ //平均值处理
int avg = 0;
vector<vector<int>> result(n,vector<int>(m));
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
avg = (R[i][j]+G[i][j]+B[i][j])/3;
result[i][j] = avg;
}
}
return result;
}
vector<vector<int>> MaxToG(vector<vector<int>>& R,vector<vector<int>>& G,vector<vector<int>>& B,int n,int m)
{ //最大值处理
int avg = 0;
vector<vector<int>> result(n,vector<int>(m));
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
avg = max(R[i][j],G[i][j]);
avg = max(avg,B[i][j]);
result[i][j] = avg;
}
}
return result;
}
void insert(vector<vector<int>>& A,int n,int m )
{ //插入函数
for(int i=0;i < n;i++){
for(int j = 0;j < m;j++){
cin>>A[i][j];
}
}
}
void outPut(vector<vector<int>>& A,int n,int m )
{ //输出函数
for(int i=0;i < n;i++){
cout<<A[i][0];
for(int j = 1;j < m;j++){
cout<<" "<<A[i][j];
}
cout<<endl;
}
}
void RGBtoGray(int n,int m,int type)
{ //总函数
vector<vector<int>> R(n,(vector<int>(m))),G(n,(vector<int>(m))),B(n,(vector<int>(m)));
insert(R,n,m);//插入
insert(G,n,m);
insert(B,n,m);
vector<vector<int>> result;
switch (type) { //选择不同的处理方法
case 0:
result = WeightedToG(R,G,B,n,m);
outPut(result,n,m);
break;
case 1:
result = AvgToG(R,G,B,n,m);
outPut(result,n,m);
break;
case 2:
result = MaxToG(R,G,B,n,m);
outPut(result,n,m);
break;
}
}
int main()
{
int n,m,type;
cin>>n>>m>>type;
RGBtoGray(n,m,type); //调用总函数
return 0;
}