OpenCV學習筆記(2)
1.像素基礎知識
(1)圖像由像素構成。圖像有以下幾種基本類型:二值圖像、灰度圖像、RGB圖像。
二值圖像:顧名思義就是一個像素點上只有兩個值,0和1,即單純的黑和白。
灰度圖像:相對於二值圖像,灰度圖像更加細膩。在單個像素點上,在黑白兩色中間增加了更多的表現色,像素點上的值也從0變到255。
RGB圖像:RGB圖片就是彩色圖片,通過三原色不同比例的混合組成多彩的圖像。RGB圖像可看成三個通道的灰度圖像的混合。
2.針對像素操作
像素的處理包括:讀取像素,修改像素。
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
char *filename = "C:/Users/Administrator/Desktop/picture/1.jpg";
Mat ImageIn=imread(filename, IMREAD_UNCHANGED);
imshow("ImageIn", ImageIn);
//int type = ImageIn.type();
int channels = ImageIn.channels();
int rows = ImageIn.rows;
int cols = ImageIn.cols;
cout <<"通道數:"<<channels<<" 行:" << rows << " 列:" << cols << endl;
for (int i = 0; i < 50; i++)//像素的遍歷
{
for (int j = 0; j < 50; j++)
{
cout <<(int)ImageIn.at<Vec3b>(i, j)[2] << " ";
ImageIn.at<Vec3b>(i, j)[2] = 0; //r通道
cout << (int)ImageIn.at<Vec3b>(i, j)[0] << " ";
ImageIn.at<Vec3b>(i, j)[0] =255;//b通道
cout << (int)ImageIn.at<Vec3b>(i, j)[1] << " ";
ImageIn.at<Vec3b>(i, j)[1] = 0; //g通道
}
cout << " "<<endl;
}
imshow("ImageIn2", ImageIn);
waitKey(0);
return 0;
}
運行效果:
其中:
(1)像素點的訪問方式:
針對單通道:
image.at(i,j);
針對三通道的訪問方式:
image.at(i,j)[0] ;
image.at(i,j)[1];
image.at(i,j)[2];
(2)OpenCV的通道順序:
OpenCV的三原色的通道順序爲BGR,並不是RGB。
3.圖像轉換
圖像的轉換也主要藉助OpenCV提供的幾個函數,特別簡單方便。
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
//顯示RGB圖像
char *filename = "C:/Users/Administrator/Desktop/picture/1.jpg";
Mat ImageRGB=imread(filename, IMREAD_UNCHANGED);
imshow("ImageRGB", ImageRGB);
//顯示灰度圖像
Mat ImageGray;
cvtColor(ImageRGB,ImageGray,COLOR_BGR2GRAY);
imshow("ImageGRAY", ImageGray);
//顯示二值圖像
Mat ImageBinary;
threshold(ImageGray, ImageBinary,100, 255, CV_THRESH_BINARY);
imshow("ImageBinary", ImageBinary);
waitKey(0);
return 0;
}
運行效果:
4.圖像融合
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
char *filename1 = "C:/Users/Administrator/Desktop/picture/1.png";
char *filename2 = "C:/Users/Administrator/Desktop/picture/2.png";
Mat ImageRGB1=imread(filename1, IMREAD_UNCHANGED);
Mat ImageRGB2 = imread(filename2, IMREAD_UNCHANGED);
imshow("ImageRGB1", ImageRGB1);
imshow("ImageRGB2", ImageRGB2);
Mat ImageAdd;
addWeighted(ImageRGB1,0.7, ImageRGB2,0.3, 0, ImageAdd);
imshow("ImageAdd", ImageAdd);
waitKey();
}
運行效果: