1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <opencv2/opencv.hpp> #include <iostream>
using namespace cv; using namespace std;
bool regionGrowing(Mat img, Mat &result, Point2i seed, int threshold){ result = Mat::zeros(img.size(), CV_8UC1);
if (seed.x < 0 || seed.y < 0 || seed.y > img.rows-1 || seed.x > img.cols-1) { return false; } vector<Point2i> seeds; seeds.push_back(seed); result.ptr<uchar>(seed.y)[seed.x] = 255; int growDirections[8][2] = {{-1,-1}, {0,-1}, {1,-1}, {-1,0}, {1,0}, {-1,1}, {0,1}, {1,1}};
while (!seeds.empty()) { Point2i seed_current = seeds.back(); seeds.pop_back(); for (int i = 0; i < 8; i++) { Point2i neighborPoint = {seed_current.x + growDirections[i][0], seed_current.y + growDirections[i][1]}; if (neighborPoint.x < 0 || neighborPoint.y < 0 || neighborPoint.x > img.cols-1 || neighborPoint.y > img.rows-1) { continue; } if ((result.ptr<uchar>(neighborPoint.y)[neighborPoint.x] == 0) && abs(img.ptr<uchar>(neighborPoint.y)[neighborPoint.x] - img.ptr<uchar>(seed.y)[seed.x]) < threshold) { result.ptr<uchar>(neighborPoint.y)[neighborPoint.x] = 255; seeds.push_back(neighborPoint); } } } return true; }
int main() { Mat img, result; img = imread("mountains.jpg", IMREAD_GRAYSCALE);
if (img.empty()) { printf("读取图像文件失败"); system("pause"); return -1; }
cout << "Select a point as seed from [" << img.rows-1 << ", " << img.cols-1 << "]" << endl; int seed_row, seed_col; cout << "row"; cin >> seed_row; cout << "col"; cin >> seed_col; Point2i seed; seed.x = seed_col; seed.y = seed_row;
int threshold = 50; regionGrowing(img, result, seed, threshold);
imshow("img",img); imshow("result",result); imwrite("result.jpg", result); waitKey(); return 0; }
|