-1

我必须通过以下步骤实现膨胀算法:-

  1. 扫描图像并将结构元素叠加在每个像素的附近。

  2. 使用结构元素执行邻域的 AND 运算。

  3. 用结构元素给出的邻域中的最大值替换像素值。

这意味着我必须检查每个像素及其与结构元素相关的邻域,如果该邻域中的任何像素为白色,则将像素更改为白色。

在这里,我部分尝试按照说明找到 ROI 中的最大值,但仍然在输出中,没有膨胀,请协助

#include <iostream>

#include<vector>

#include<math.h>

#include<string>

#include<time.h>

#include <opencv2/core.hpp>

#include <opencv2/objdetect.hpp>

#include <opencv2/imgcodecs.hpp>

#include <opencv2/imgproc.hpp>

#include <opencv2/highgui.hpp>

#include <opencv2/opencv.hpp>

#include <opencv2/videoio.hpp>

using namespace std;

using namespace cv;

int main()
{
    Mat demoImage = Mat::zeros(Size(10, 10), CV_8U);
    
    //Adding some White blobs to the image
    demoImage.at<uchar>(0, 1) = 1;
    demoImage.at<uchar>(9, 0) = 1;
    demoImage.at<uchar>(8, 9) = 1;
    demoImage.at<uchar>(2, 2) = 1;
    demoImage(Range(5, 8), Range(5, 8)).setTo(1);
    std::cout << demoImage << std::endl;
    
    //Structuring Element
    Mat element = getStructuringElement(MORPH_CROSS, Size(3, 3));
    
    int ksize = element.size().height; 

    //Dimensions of the src image
    int height, width;
    height = demoImage.size(). height;
    width = demoImage.size().width;

    int border = ksize / 2;
    Mat paddedDemoImage = Mat::zeros(Size(height + border * 2, width + border * 2), CV_8UC1);
    copyMakeBorder(demoImage, paddedDemoImage, border, border, border, border, BORDER_CONSTANT, 0);

    Mat paddedDilatedImage = paddedDemoImage.clone();
    Mat mask;

    double minVal, maxVal;

    //Create video writer object
    cv::VideoWriter output;
    output.open("dilationScratch.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 10, Size(50, 50));


    for (int h_i = border; h_i < height + border; h_i++) {          //Traversing rows

        for (int w_i = border; w_i < width + border; w_i++) {       //Traversing columns

            if (demoImage.at<uchar>(h_i - border, w_i - border) == 1) {

                cout << "White Pixel Found at " << h_i << "," << w_i << endl;

                Mat demoROI = paddedDemoImage(Range(h_i - border, h_i + border + 1), Range(w_i - border, w_i + border + 1));

                bitwise_and(demoROI, element, mask);

                minMaxLoc(mask, &minVal, &maxVal);

                std::cout << "Maximum" << maxVal << std::endl;

                paddedDemoImage.at<uchar>(h_i, w_i) = maxVal;

            }

            paddedDilatedImage = paddedDemoImage(Range(border, border + height), Range(border, border + width));
            resize(paddedDilatedImage, paddedDilatedImage, cv::Size(50, 50), INTER_LINEAR);
            cv::cvtColor(paddedDilatedImage, paddedDilatedImage, COLOR_GRAY2BGR);

            output.write(paddedDilatedImage * 255);
        }

    }

    //Release the output frame
    output.release();

    waitKey(0);

    return 0;
}

现在我可以识别白色或 1 个像素,但是我该如何推进上面的算法,请帮忙。

4

0 回答 0