溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

OpenCV如何根據(jù)面積篩選連通域

發(fā)布時(shí)間:2022-06-07 10:18:47 來源:億速云 閱讀:191 作者:zzz 欄目:開發(fā)技術(shù)

這篇文章主要介紹“OpenCV如何根據(jù)面積篩選連通域”,在日常操作中,相信很多人在OpenCV如何根據(jù)面積篩選連通域問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”O(jiān)penCV如何根據(jù)面積篩選連通域”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

示例代碼

//src為二值圖,minArea、maxArea為面積閾值,dest為結(jié)果圖像
void connectionAreaSelect(Mat src, int minArea, int maxArea, Mat &dest)
{
	Mat labels, stats, centroids, img_color;
	//連通域計(jì)算
	int nccomps = connectedComponentsWithStats(
		src, //二值圖像
		labels,
		stats,
		centroids
	);

	//去除過小區(qū)域,初始化顏色表
	vector<Vec3b> colors(nccomps);
	colors[0] = Vec3b(0, 0, 0); // background pixels remain black.
	for (int i = 1; i < nccomps; i++)
	{
		colors[i] = Vec3b(rand() % 256, rand() % 256, rand() % 256);

		//面積閾值篩選
		int holeArea = stats.at<int>(i, CC_STAT_AREA);
		if ((holeArea < minArea) || (holeArea > maxArea))
		{
			colors[i] = Vec3b(0, 0, 0);
		}
	}
	//按照label值,對(duì)不同的連通域進(jìn)行著色
	img_color = Mat::zeros(src.size(), CV_8UC3);
	for (int y = 0; y < img_color.rows; y++)
	{
		for (int x = 0; x < img_color.cols; x++)
		{
			int label = labels.at<int>(y, x);
			CV_Assert(0 <= label && label <= nccomps);
			img_color.at<Vec3b>(y, x) = colors[label];
		}
	}
	//統(tǒng)計(jì)降噪后的連通區(qū)域
	Mat grayImg;
	cvtColor(img_color, grayImg, COLOR_BGR2GRAY);
	threshold(grayImg, grayImg, 1, 255, THRESH_BINARY);
	dest = grayImg.clone();

	labels.release();
	stats.release();
	centroids.release();
	img_color.release();
	grayImg.release();
}

到此,關(guān)于“OpenCV如何根據(jù)面積篩選連通域”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI