使用OpenCV获取图片连通域数量,并用不同颜色标记函


Posted in Python onJune 04, 2020

一,原图和效果图

使用OpenCV获取图片连通域数量,并用不同颜色标记函

二,代码

//#########################产生随机颜色#########################
cv::Scalar icvprGetRandomColor()
{
	uchar r = 255 * (rand() / (1.0 + RAND_MAX));
	uchar g = 255 * (rand() / (1.0 + RAND_MAX));
	uchar b = 255 * (rand() / (1.0 + RAND_MAX));
	return cv::Scalar(b, g, r);
}
//#########################产生随机颜色#########################

//########################种子填充法)#########################
void ConnectedCountBySeedFill(const cv::Mat& _binImg, cv::Mat& _lableImg, int &iConnectedAreaCount)
{
  //拓宽1个像素的原因是:如果连通域在边缘,运行此函数会异常崩溃,所以需要在周围加一圈0值,确保连通域不在边上
	//==========图像周围拓宽1个像素============================================
	int top, bottom;      //【添加边界后的图像尺寸】
	int leftImage, rightImage;
	int borderType = BORDER_CONSTANT; //BORDER_REPLICATE
	//【初始化参数】
	top = (int)(1); bottom = (int)(1);
	leftImage = (int)(1); rightImage = (int)(1);
	Mat _binImg2, _binImg3;
	_binImg.copyTo(_binImg2);
		//初始化参数value
		Scalar value(0); //填充值
		//创建图像边界
		copyMakeBorder(_binImg2, _binImg3, top, bottom, leftImage, rightImage, borderType, value);

	//==========图像周围拓宽1个像素============================================

	// connected component analysis (4-component) 
	// use seed filling algorithm 
	// 1. begin with a foreground pixel and push its foreground neighbors into a stack; 
	// 2. pop the top pixel on the stack and label it with the same label until the stack is empty 
	//  
	// foreground pixel: _binImg(x,y) = 1 
	// background pixel: _binImg(x,y) = 0 

	if (_binImg3.empty() ||
		_binImg3.type() != CV_8UC1)
	{
		return;
	}

	_lableImg.release();
	_binImg3.convertTo(_lableImg, CV_32SC1);
	int icount = 0;
	int label = 1; // start by 2 

	int rows = _binImg3.rows - 1;
	int cols = _binImg3.cols - 1;
	for (int i = 1; i < rows - 1; i++)
	{
		int* data = _lableImg.ptr<int>(i);  //取一行数据
		for (int j = 1; j < cols - 1; j++)
		{
			if (data[j] == 1)  //像素不为0
			{
				std::stack<std::pair<int, int>> neighborPixels;   //新建一个栈
				neighborPixels.push(std::pair<int, int>(i, j));   // 像素坐标: <i,j> ,以该像素为起点,寻找连通域 
				++label; // 开始一个新标签,各连通域区别的标志
				while (!neighborPixels.empty())
				{
					// 获取堆栈中的顶部像素并使用相同的标签对其进行标记
					std::pair<int, int> curPixel = neighborPixels.top();
					int curX = curPixel.first;
					int curY = curPixel.second;
					_lableImg.at<int>(curX, curY) = label; //对图像对应位置的点进行标记

					// 弹出顶部像素  (顶部像素出栈)
					neighborPixels.pop();

						// 加入8邻域点
						if (_lableImg.at<int>(curX, curY - 1) == 1)
						{// 左点 
							neighborPixels.push(std::pair<int, int>(curX, curY - 1)); //左边点入栈
						}

						if (_lableImg.at<int>(curX, curY + 1) == 1)
						{// 右点 
							neighborPixels.push(std::pair<int, int>(curX, curY + 1)); //右边点入栈
						}

						if (_lableImg.at<int>(curX - 1, curY) == 1)
						{// 上点 
							neighborPixels.push(std::pair<int, int>(curX - 1, curY)); //上边点入栈
						}

						if (_lableImg.at<int>(curX + 1, curY) == 1)
						{// 下点 
							neighborPixels.push(std::pair<int, int>(curX + 1, curY)); //下边点入栈
						}
						//===============补充到8连通域======================================================
						if (_lableImg.at<int>(curX - 1, curY - 1) == 1)
						{// 左上点 
							neighborPixels.push(std::pair<int, int>(curX - 1, curY - 1)); //左上点入栈
						}

						if (_lableImg.at<int>(curX - 1, curY + 1) == 1)
						{// 右上点 
							neighborPixels.push(std::pair<int, int>(curX - 1, curY + 1)); //右上点入栈
						}

						if (_lableImg.at<int>(curX + 1, curY - 1) == 1)
						{// 左下点 
							neighborPixels.push(std::pair<int, int>(curX + 1, curY - 1)); //左下点入栈
						}

						if (_lableImg.at<int>(curX + 1, curY + 1) == 1)
						{// 右下点 
							neighborPixels.push(std::pair<int, int>(curX + 1, curY + 1)); //右下点入栈
						}
					//===============补充到8连通域======================================================
				}
			}
		}
	}
	iConnectedAreaCount = label - 1; //因为label从2开始计数的
	int a = 0;
}
###########################################################
//#############添加颜色#####################################
Mat PaintColor(Mat src, int iConnectedAreaCount)
{
	int rows = src.rows;
	int cols = src.cols;

	//cv::Scalar(b, g, r);
	std::map<int, cv::Scalar> colors;
	for (int n = 1; n <= iConnectedAreaCount + 1; n++)
	{
		colors[n] = icvprGetRandomColor(); //根据不同标志位产生随机颜色

		cv::Scalar color = colors[n];
		int a = color[0];
		int b = color[1];
		int c = color[2];
		int d = 0;
	}

	Mat dst2(rows, cols, CV_8UC3);
	dst2 = cv::Scalar::all(0);
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
		{
			int value = src.at<int>(i, j);
			if (value>1)
			{
				cv::Scalar color = colors[value];
				int a = color[0];
				int b = color[1];
				int c = color[2];
				dst2.at<Vec3b>(i, j)[0] = color[0];
				dst2.at<Vec3b>(i, j)[1] = color[1];
				dst2.at<Vec3b>(i, j)[2] = color[2];
			}
		}
	}
	return dst2;
}
//#############添加颜色##################################

//########调用##########################################
  Mat binImage = cv::imread("D:\\sxl\\处理图片\\testImages\\22.jpg", 0);
	threshold(binImage, binImage, 50, 1, CV_THRESH_BINARY_INV);

	// 连通域标记 
	Mat labelImg;
	int iConnectedAreaCount = 0; //连通域个数
	ConnectedCountBySeedFill(binImage, labelImg, iConnectedAreaCount);//针对黑底白字
	int a=iConnectedAreaCount;
	
	// 显示结果
	Mat dstColor2=PaintColor(labelImg,iConnectedAreaCount);
	imshow("colorImg", dstColor2);

	Mat grayImg;
	labelImg *= 10;
	labelImg.convertTo(grayImg, CV_8UC1);
	imshow("labelImg", grayImg);

	waitKey(0);
//########调用##########################################

补充知识:Opencv快速获取连通域

对于ndarray数据中的连通域查找,opencv提供了接口,非常方便。

import cv2
import numpy as np

img = np.array([
  [0, 255, 255, 0, 0, 0, 255, 255,],
  [0, 0, 255, 0, 255, 255, 255, 0],
  [0, 0, 0, 0, 255, 255, 0, 255],
  [255, 255, 0, 0, 0, 0, 0, 0],
  [255, 255, 0, 0, 0, 0, 0, 0],
  [255, 255, 0, 0, 0, 0, 0, 0]
], dtype=np.uint8)

num, labels = cv2.connectedComponents(img)
labels_dict = {i:[] for i in range(1, num+1)}
height, width = img.shape
for h in range(height):
  for w in range(width):
    if labels[h][w] in labels_dict:
      labels_dict[labels[h][w]].append([h,w])

cv2.connectedComponents()函数返回查找到的连通域个数和对应的label。

上面代码返回连通域个数为4(包含值为0区域,可通过lables过滤), labels结果如图所示:

使用OpenCV获取图片连通域数量,并用不同颜色标记函

以上这篇使用OpenCV获取图片连通域数量,并用不同颜色标记函就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python BeautifulSoup使用方法详解
Nov 21 Python
Python爬虫爬验证码实现功能详解
Apr 14 Python
python实现网页自动签到功能
Jan 21 Python
解决Python3 被PHP程序调用执行返回乱码的问题
Feb 16 Python
python 实现将多条曲线画在一幅图上的方法
Jul 07 Python
python Gunicorn服务器使用方法详解
Jul 22 Python
Python中调用其他程序的方式详解
Aug 06 Python
使用python绘制二维图形示例
Nov 22 Python
python 实现批量替换文本中的某部分内容
Dec 13 Python
Python实现UDP程序通信过程图解
May 15 Python
浅谈TensorFlow之稀疏张量表示
Jun 30 Python
Python Matplotlib绘制两个Y轴图像
Apr 13 Python
Python urllib2运行过程原理解析
Jun 04 #Python
Python如何生成xml文件
Jun 04 #Python
基于python代码批量处理图片resize
Jun 04 #Python
Python脚本如何在bilibili中查找弹幕发送者
Jun 04 #Python
Python爬虫谷歌Chrome F12抓包过程原理解析
Jun 04 #Python
python实现按键精灵找色点击功能教程,使用pywin32和Pillow库
Jun 04 #Python
解决python图像处理图像赋值后变为白色的问题
Jun 04 #Python
You might like
如何对PHP程序中的常见漏洞进行攻击(上)
2006/10/09 PHP
php中is_null,empty,isset,unset 的区别详细介绍
2013/04/28 PHP
跟我学Laravel之配置Laravel
2014/10/15 PHP
php pdo oracle中文乱码的快速解决方法
2016/05/16 PHP
Javascript与flash交互通信基础教程
2008/08/07 Javascript
JavaScript极简入门教程(三):数组
2014/10/25 Javascript
jquery实现对联广告的方法
2015/02/05 Javascript
详解JavaScript的回调函数
2015/11/20 Javascript
轻松学习jQuery插件EasyUI EasyUI实现树形网络基本操作(2)
2015/11/30 Javascript
JavaScript中对JSON对象的基本操作示例
2016/05/21 Javascript
js实现时间轴自动排列效果
2017/03/09 Javascript
Bootstrap3.3.7导航栏下拉菜单鼠标滑过展开效果
2017/10/31 Javascript
解决Mac安装thrift因bison报错的问题
2018/05/17 Javascript
深入理解NodeJS 多进程和集群
2018/10/17 NodeJs
实现elementUI表单的全局验证的方法步骤
2019/04/29 Javascript
vue transition 在子组件中失效的解决
2019/11/12 Javascript
[01:25]2014DOTA2国际邀请赛 zhou分析LGD比赛情况
2014/07/14 DOTA
[49:35]2018DOTA2亚洲邀请赛3月30日 小组赛A组 KG VS TNC
2018/03/31 DOTA
Python3实现发送QQ邮件功能(附件)
2020/12/23 Python
Python简单爬虫导出CSV文件的实例讲解
2018/07/06 Python
对python中的argv和argc使用详解
2018/12/15 Python
Python父目录、子目录的相互调用方法
2019/02/16 Python
python3.6+selenium实现操作Frame中的页面元素
2019/07/16 Python
简单了解django处理跨域请求最佳解决方案
2020/03/25 Python
python接口自动化之ConfigParser配置文件的使用详解
2020/08/03 Python
CSS3条纹背景制作的实战攻略
2016/05/31 HTML / CSS
美国网上订购鲜花:FTD
2016/09/23 全球购物
Fairyseason:为个人和批发商提供女装和配件
2017/03/01 全球购物
医师定期考核实施方案
2014/05/07 职场文书
英文邀请函
2015/02/02 职场文书
内勤岗位职责范本
2015/04/13 职场文书
学生会主席任命书
2015/09/21 职场文书
2015年美容师个人工作总结
2015/10/14 职场文书
2016年国培心得体会及反思
2016/01/13 职场文书
《生物入侵者》教学反思
2016/02/16 职场文书
Python几种酷炫的进度条的方式
2022/04/11 Python