阈值分割和形态学变换
作者:
地球OLBug
,
2022-10-14 15:40:46
,
所有人可见
,
阅读 194
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
void threshold(Mat img, Mat &res, int threshold = 160)
{
img.copyTo(res);
int n = res.rows;
int m = res.cols * res.channels();
for (int i = 0; i < n; i++)
{
uchar* data = res.ptr<uchar>(i);
for (int j = 0; j < m; j++) {
data[j] = data[j] > threshold;
}
}
}
int main() {
Mat img = imread("G:/image/xs.jpg");
cvtColor(img, img, COLOR_BGR2GRAY);
cout << img.rows << ' ' << img.cols << '\n';
resize(img, img, Size(256, 256), INTER_AREA);
cout << img.rows << ' ' << img.cols << '\n';
Mat Binary, Erode, Dilate, element;
threshold(img, Binary);
int kernel_size = 5;
element = getStructuringElement(MORPH_RECT, Size(5, 5));
erode(Binary, Erode, element);
dilate(Binary, Dilate, element);
imshow("Original image", img);
imshow("Binary_image",Binary * 255 );
imshow("Erode_image",Erode * 255);
imshow("Dilate_image", Dilate * 255);
waitKey(0);
return 0;
}