针对灰度图像
1. 腐蚀
实现:在图像f中的某一像素点,以结构元素B的中心位置处对应该像素点, 若以该像素点为中心,寻找在结构元素B大小覆盖的邻域范围内(图像f上) 的最小值来代替该点像素值,作为腐蚀后对应位置的像素;简言之,邻域内(局部)最小值来代替该点像素。
主要作用:腐蚀过的图像一般背景比原图像要稍暗一些,比结构元b小的亮度特征被腐蚀掉了;
c++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void gray_erode(Mat &src, Mat &dst, int n) { std::vector<float> winTotal; src.copyTo(dst); int windows_size = n*n; int edge = n / 2; for (int i = edge; i < src.rows - edge; i++) { uchar * dstptr = dst.ptr(i); for (int j = edge; j < src.cols - edge; j++) { winTotal.clear(); for (int x = -edge; x <= edge; x++) { for (int y = -edge; y <= edge; y++) { winTotal.push_back(src.at<uchar>(i + x, j + y)); } } std::sort(winTotal.begin(), winTotal.end()); /*for (int t = 0; t < winTotal.size(); t++) cout << t << ", " << winTotal[t] << endl;*/ dstptr[j] = winTotal[0]; } } }
2. 膨胀
实现:参考上述腐蚀的实现,只不过这里是用局部最大值来代替;
c++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void gray_dilate(Mat &src, Mat &dst, int n) { std::vector<float> winTotal; src.copyTo(dst); int windows_size = n*n; int edge = n / 2; for (int i = edge; i < src.rows - edge; i++) { uchar * dstptr = dst.ptr(i); for (int j = edge; j < src.cols - edge; j++) { winTotal.clear(); for (int x = -edge; x <= edge; x++) { for (int y = -edge; y <= edge; y++) { winTotal.push_back(src.at<uchar>(i + x, j + y)); } } std::sort(winTotal.begin(), winTotal.end()); /*for (int t = 0; t < winTotal.size(); t++) cout << t << ", " << winTotal[t] << endl;*/ dstptr[j] = winTotal[winTotal.size()-1]; } } }
3. 开操作
实现:先腐蚀(局部最小值),后膨胀(局部最大值);
主要作用:开操作用于去除较小的明亮细节,而保持整体灰度级和较大的明亮特征相对不变;
c++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void gray_openOperation(Mat &src, Mat &dst, int n) { Mat src_temp; gray_erode(src, src_temp, n); gray_dilate(src_temp, dst, n); }
4. 闭操作
实现:先膨胀(局部最大值),后腐蚀(局部最小值);
主要作用:闭操作主要用于削弱暗特征,削弱的程度取决于这些特征相对于结构元的尺寸,而亮的细节和背景相对来说未受影响;
c++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void gray_closeOperation(Mat &src, Mat &dst, int n) { Mat src_temp; gray_dilate(src, src_temp, n); gray_erode(src_temp, dst, n); }
5. 顶帽变换
实现:图像f减去其开操作;
主要作用:顶帽变换用于暗背景上的亮物体(有待后续完善...);
c++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void gray_topHat(Mat &src, Mat &dst, int n) { Mat src_temp; gray_openOperation(src, src_temp, n); if (src.rows == src_temp.rows && src.cols == src_temp.cols && src.type() == src_temp.type()) { subtract(src, src_temp, dst); } }
6. 底帽操作
实现:图像f的闭操作减去图像f;
主要作用:底帽作用用于亮背景上的暗物体(有待后续完善...)
c++实现代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void gray_bottomCap(Mat &src, Mat &dst, int n) { Mat src_temp; gray_closeOperation(src, src_temp, n); if (src.rows == src_temp.rows && src.cols == src_temp.cols && src.type() == src_temp.type()) { subtract(src_temp, src, dst); } }