给出一个正方形图像,中间为一不白色规则图形,周围图像为黑色,实现图像读取,分割后输出两个目标图像。
#include<iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main() {
int T0 = 200, T1 = 0, limit = 10;
// 读入pic1
Mat img = imread("C:\\Users\\Administrator\\Desktop\\pic1.png", 0);
Mat G1, G2;
//得到行数与列数
int r = img.rows;
int c = img.cols;
bool quit = false;
while (!quit) {
img.copyTo(G1);
img.copyTo(G2);
int num_G1 = 0, num_G2 = 0;
long int sum_G1 = 0, sum_G2 = 0;
for (int j = 0; j < r; j++) {
uchar* data = img.ptr<uchar>(j);
uchar* g1 = G1.ptr<uchar>(j);
uchar* g2 = G2.ptr<uchar>(j);
for (int i = 0; i < c; i++) {
int piexl = data[i];
// G1用于存放较暗部分
if (piexl < T0) {
num_G1++;
sum_G1 += piexl;
// 将G2较暗部分置黑
g2[i] = 0;
// G2用于存放明亮部分
}
else {
num_G2++;
sum_G2 += piexl;
// 将G1明亮部分置黑
g1[i] = 0;
}
}
}
// 得到新的阈值
T1 = T0;
T0 = (sum_G1 / num_G1 + sum_G2 / num_G2) * 0.5;
// 分割完毕
if (T1 - T0 < limit) {
quit = true;
// 输出G2图像
cvNamedWindow("result");
imshow("result", G2);
waitKey(NULL);
}
}
}
主要通过将图像读入矩阵中然后根据RGB值进行各个点的归类实现图像分割。