#include "iostream" #include "algorithm" #include "opencv2/opencv.hpp" using namespace cv; using namespace std; int main() { string imgPath = "D:qtprojectimg8.png"; Mat img = imread(imgPath); if(img.empty()) { cout<<imgPath<<" not exit!"<<endl; return 0; } Mat dilate_my; dilate_my.create(img.rows, img.cols, CV_8UC1); for(int i = 0; i<img.rows;++i) { for(int j = 0; j<img.cols; ++j) { /*巧妙设计:滤波器中的像素遍历,起止点*/ uchar maxV=0; for(int yi = i-1; yi <= i+1; yi++) { for(int xi = j-1; xi <=j+1; xi++) { /*截至条件设计*/ if(xi<0||xi>=img.cols||yi<0||yi>=img.rows) { continue; } maxV = (std::max<uchar>)(maxV, img.at<uchar>(yi, xi)); } } dilate_my.at<uchar>(i, j) = maxV; } } return 0; }