以前只知道用Scalar给所有的像素赋同样的初值,现在终于知道怎么完整的赋值了:
uchar m[3][3]={{1,2,3},{1,2,3},{1,2,3}};
Mat M(3,3,CV_8UC1,m);
cout<<M<<endl;
uchar a=M.at<uchar>(1);
printf("%d",a);
cout<<a<<endl;
其中CV_8U对应uchar类型,但是用cout输出会出现笑脸。(原因暂时不懂)
程序运行时间的代码:单位为s
double t=(double)getTickCount();
...
t=(getTickCount()-t)/getTickFrequency();
前天老师布置了这样一个任务:选一幅彩色图片将其灰度值介于120——140之间的像素显示红色即(0,0,255)
以下是自己写的代码:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat src,dst,gray;
vector<Mat> Channels;
Mat BlueChannel,GreenChannel,RedChannel;
int a=120,b=140;//变化的上下限
src=imread("lena.jpg",1);
if (!src.data) {cout<<"src error!!!"<<endl;return -1;}
//src=src(Rect(100,100,10,10));//RIO 测试
split(src,Channels);//通道分离
BlueChannel=Channels.at(0);
GreenChannel=Channels.at(1);
RedChannel=Channels.at(2);
cvtColor(src,gray,COLOR_BGR2GRAY);
Mat min(gray.size(),gray.type(),Scalar(a));
Mat max(gray.size(),gray.type(),Scalar(b));
Mat red=(gray>min)&(gray<max);
BlueChannel=BlueChannel-red;//有溢出保护,可不用循环
GreenChannel=GreenChannel-red;
RedChannel=RedChannel+red;
merge(Channels,dst);
//cout<<src<<endl;
//cout<<RedChannel<<endl;
//cout<<red<<endl;
//printf("%d",src.at<uchar>(0));//用cout会出现图标,而不是数字
imshow("原始图像",src);
imshow("变化的位置(a,b)",red);
imshow("变化后图像",dst);
waitKey(0);
return 0;
}
随机数产生函数:rand(),用rand()%m可产生一个0-m-1的随机数
int b[9],i;
uchar m[3][3]={{1,2,3},{1,2,3},{1,2,3}};
Mat M(3,3,CV_8UC1,m);
for(i=0;i<9;i++)
{
b[i]=(uchar)rand()%10;
M.at<uchar>(i)=b[i];
printf("p:%d\t",b[i]);
cout<<"c:"<<b[i]<<endl;
}
cout<<b<<endl;
cout<<M<<endl;
此程序产生0-9的随机数,但是输出
cout<<b<<endl;
的时候和循环里的输出不一致,而且每次都不一样,这个问题只能暂时放到这里了。
随机数产生函数可以用来给图像加随机白噪声:(参考大神的博文)
void salt(Mat& image, int n)
{
for(int k=0; k<n; k++)
{
int i = rand()%image.cols;
int j = rand()%image.rows;
if(image.channels() == 1)
{
image.at<uchar>(j,i) = 255;
}
else
{
image.at<Vec3b>(j,i)[0] = 255;
image.at<Vec3b>(j,i)[1] = 255;
image.at<Vec3b>(j,i)[2] = 255;
}
}
}
自写代码:
bool salt(Mat image,int n)
{
int i,j,k;
for(k=0;k<n;k++)
{
i=rand()%10;
j=rand()%10;
image.at<uchar>(i,j)=255;
printf("i=%d,j=%d\n",i,j);
}
return 1;
}
int main()
{
Mat M(10,10,CV_8UC1,Scalar(0));
if(salt(M,10))
cout<<M<<endl;
waitKey(0);
return 0;
}
用小点的数组来模拟可以清楚的看出行列的对应关系。
int main()
{
int b[100],i;
for(i=0;i<100;i++)
b[i]=rand()%255;
Mat M(10,10,CV_8UC1,b);
Mat N,L;
blur(M, N,Size(3, 3)); //均值滤波
medianBlur(M,L,3);//中值滤波
if(salt(M,10))
cout<<M<<endl;
cout<<N<<endl;
cout<<L<<endl;
waitKey(0);
return 0;
}
以上代码可以很清楚的看出两种滤波对白噪声的去噪效果。(不知为什么我随机产生的数组b出现0的概率很大,所以中值滤波后全为0)
OK,今天就到这里把,明天还要练车。