matlab imregionalmax/imregionalmin 函数 C++实现

来源:互联网 发布:淘宝代理加盟的骗局 编辑:程序博客网 时间:2024/06/13 19:51

在将matlab程序改为C++版时候,用到了imregionalmax、imregionalmin 来实现矩阵行列的局部极值的求解。

格式:imregionalmax(A,n)
说明:A可以使2D数据或3D数据,n为求局部极值所采用的方法,默认2D时n=8(八邻域法);3D时n=26.2D时,n=4/8;3D时,n=6/18/26 。
返回值:一个二值逻辑矩阵,结构与A相同(1:表示局部极大值;0表示:非局部极大值)。



matlab中的运行结果如上图。

更加详细的内容可参考:matlab 一维离散数据的极值及极值位置的计算


实验中需求的是对于一行图像数据的求解,转换的C++代码如下
int FindFirstDiffNum(const vector<int> &num, vector<int> &peakValley, unsigned startPos, int flag){if (flag > 0) //找下一个最右值波峰的位置  如: 1 2 3 4 4 4 3 2  最后一个波峰的位置为5,第三个4{for (unsigned i = startPos; i < num.size() - 1; i++){if (num[i + 1] < num[i]){peakValley[i] = 1;//逆序寻找此局部极值的最左端for (unsigned j = i - 1; j > startPos; j--)  // 可改为只取两端{if (num[j] == num[i])peakValley[j] = 1;elsebreak;}return i; //返回最后一个的位置}else{continue;}}return 0;}else  //找下一个最右值波谷的位置  如: 4 4 4 3 2 2 5 5  最后一个波谷的位置为5,第二个2{for (unsigned i = startPos; i < num.size() - 1; i++){if (num[i + 1] > num[i]){peakValley[i] = -1;for (unsigned j = i - 1; j > startPos; j--)  // 可改为只取两端{if (num[j] == num[i])peakValley[j] = -1;elsebreak;}return i;}else{continue;}}return 0;}}// 数据中可能的极值点//  num: the input array, only a row/col// peakValley: the output array, only contents 0,1;  1---peaks, 0---valleyvoid findPeaks(const vector<int> &num, vector<int> &peakValley){unsigned count = 0;int dif = 0;int ret = 0;while (count < num.size() - 1){dif = num[count + 1] - num[count];if (dif == 0){count++;continue;}if (dif < 0)  //以减序开始{ret = FindFirstDiffNum(num, peakValley, count, -1);if (ret > 0)   //重新赋值新的起始位置count = ret;else    //否则就是这一行搜索到头了break;}else{ret = FindFirstDiffNum(num, peakValley, count, 1);if (ret > 0)count = ret;elsebreak;}}}int main(int argc, char* argv[]){int arr[] = { 15, 18, 19, 145, 168, 255, 255, 255, 234, 168, 11, 11, 15, 11, 11, 84, 84, 26, 57, 88 };vector<int> data;vector<int> peakValley(20, 0);for (int i = 0; i< sizeof(arr)/sizeof(int); i++){data.push_back(arr[i]);}findPeaks(data, peakValley);for (unsigned j = 0; j < peakValley.size(); j++){cout << peakValley[j] << " ";}cout << endl;return 0;}


结果展示:



对比结果:matlab将头和尾均计算在内了,可根据实际需要进行调整。