中北大学安卓实验室培训课程-计算机视觉(1) ——卷积与opencv
详细代码:
一、摄像机与视频的读取
VideoCapture cap(0);
while (true)
{
Mat frame;
cap>>frame;
namedWindow("123",0);
imshow("123",frame);
waitKey(30);
}
二、读取图片 与其中的像素值
Mat imggray=imread("123.jpg",1);
cvtColor(imggray,imggray,CV_RGB2GRAY);
cout<<(int)imggray.at<uchar>(1,1)<<endl;
imshow("123",imggray);
waitKey(0);
三、Mat对象一些操作
Mat imgone=Mat::ones(5,5,CV_64FC1);
Mat sum=image*imgone;
cout<<sum<<endl;
Mat image=Mat::eye(5,5,CV_64FC1);
image.inv();
四、图像x方向求导的卷积与非卷积操作
VideoCapture cap(0);
while (true)
{
Mat frame;
cap>>frame;
cvtColor(frame,frame,CV_RGB2GRAY);
/*cout<<"row"<<frame.rows<<" col"<<frame.cols<<endl;
Mat dimg=Mat(frame.rows,frame.cols-2,CV_8UC1);
for (int i=0;i<frame.rows;i++)
{
for (int j=1;j<frame.cols-1;j++)
{
dimg.at<uchar>(i,j-1)=frame.at<uchar>(i,j-1)-frame.at<uchar>(i,j+1);
}
}*/
Mat dimg=Mat(frame.rows,frame.cols-2,CV_8UC1);
Mat model=Mat(1,3,CV_64FC1);
model.at<double>(0,0)=1;
model.at<double>(0,1)=0;
model.at<double>(0,2)=-1;
for(int i=0;i<frame.rows;i++){
for (int j=1;j<frame.cols-1;j++)
{
int half=model.cols/2;
double sum=0;
for (int m=0;m<model.rows;m++)
{
for (int n=-half;n<model.cols-half;n++)
{
sum+=(double)(frame.at<uchar>(i+m,j+n))*model.at<double>(m,n+half);
}
}
dimg.at<uchar>(i,j-1)=(uchar)sum;
}
}
imshow("123",dimg);
waitKey(10);
}
五、高斯模糊的核创建与卷积操作
double sigma=50;
Mat gauss(5,5,CV_64FC1);
for (int i=-2;i<3;i++)
{
for (int j=-2;j<3;j++)
{
gauss.at<double>(i+2,j+2)=exp(-(i*i+j*j)/(2*sigma*sigma));
}
}
double gssum=sum(gauss).val[0];
for (int i=-2;i<3;i++)
{
for (int j=-2;j<3;j++)
{
gauss.at<double>(i+2,j+2)/=gssum;
}
}
//cout<<gauss<<endl;
VideoCapture cap(0);
while (true){
Mat frame;
cap>>frame;
cvtColor(frame,frame,CV_RGB2GRAY);
Mat dimg=Mat(frame.rows-4,frame.cols-4,CV_8UC1);
for (int i=2;i<frame.rows-2;i++)
{
for (int j=2;j<frame.cols-2;j++)
{
double sum=0;
for (int m=0;m<gauss.rows;m++)
{
for (int n=0;n<gauss.cols;n++)
{
sum+=(double)(frame.at<uchar>(i+m-2,j+n-2))*gauss.at<double>(m,n);
}
}
dimg.at<uchar>(i-2,j-2)=(uchar)sum;
}
}
imshow("a",frame);
imshow("gauss",dimg);
waitKey(10);
}
六、相关API操作
VideoCapture cap(0);
while (true)
{
Mat frame;
cap>>frame;
cvtColor(frame,frame,CV_RGB2GRAY);
//GaussianBlur(frame,frame,cvSize(5,5),10,10);
//Canny(frame,frame,100,100);
//Sobel(frame,frame,0,1,1);
imshow("q",frame);
waitKey(10);
}