图像分割

给出一个正方形图像,中间为一不白色规则图形,周围图像为黑色,实现图像读取,分割后输出两个目标图像。

#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值进行各个点的归类实现图像分割。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值