opencv庫練習--參考SLAM十四講5.3
#include <iostream>
using namespace std;
#include <chrono>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
int main(int argc, char **argv)
{
cv::Mat image;
// image=cv::imread("ubuntu.png");
image=cv::imread(argv[1]);
if(image.data==nullptr){
cerr<<"檔案"<<argv[1]<<"不存在."<<endl;
return 0;
}
cout<<"影象寬為(列):"<<image.cols<<",高為:"<<image.rows<<",通道數為:"<<image.channels()<<endl;
cv::imshow("image",image);//彩色圖型別一般CV_8UC3,灰度圖CV_8UC1
cv::waitKey(0);
chrono::steady_clock::time_point t1=chrono::steady_clock::now();
for(int i=0;i<image.rows;i++){
cv::Vec3b *p=image.ptr<cv::Vec3b>(i);
for(int j=0;j<image.cols;j++){
for(int k=0;k!=image.channels();k++){
uchar data =p[j][k];//對每一通道進行訪問
}
}
}
//算一下遍歷所有畫素點一張圖的時間
chrono::steady_clock::time_point t2=chrono::steady_clock::now();
chrono::duration<double> time_used =chrono::duration_cast<chrono::duration<double>>(t2-t1);
cout<<"遍歷影象時間"<<time_used.count()<<" 秒"<<endl;
cv::Mat image_another =image;
image_another(cv::Rect(0,0,100,100)).setTo(255);//將左上角100*100至255,白色,最亮。
cv::imshow("image_another",image_another);
cv::waitKey(0);
cv::Mat image_clone=image.clone();
image_clone(cv::Range(0,100),cv::Range::all()).setTo(0);
cv::imshow("image_clone",image_clone);
cv::waitKey(0);
/*下面試試cv中對影象的一些處理操作*/
cv::Mat gray_image(600,800,CV_8UC1);
cv::Mat color_image(600,800,CV_8UC3);
for(int i=0;i<gray_image.rows;i++){
uchar *p=gray_image.ptr<uchar>(i);
for(int j=0;j<gray_image.cols;j++){
p[j]=(i+j)%255;//往右下有黑漸變白的特徵且有重複出現
}
}
cv::imshow("gray_image",gray_image);
for(int i=0;i<color_image.rows;i++){
cv::Vec3b *p=color_image.ptr<cv::Vec3b>(i);
for(int j=0;j<color_image.cols;j++){
p[j][0]=i%255;//Blue也可以採用rand函式試試
p[j][1]=j%255;//Green
p[j][2]=0;//Red
}
}
cv::imshow("color_image",color_image);
cv::waitKey(0);
return 0;
}