使用OpenCV獲取圖片連通域數(shù)量,并用不同顏色標(biāo)記函
一,原圖和效果圖
二,代碼
//#########################產(chǎn)生隨機(jī)顏色######################### 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); } //#########################產(chǎn)生隨機(jī)顏色######################### //########################種子填充法)######################### void ConnectedCountBySeedFill(const cv::Mat& _binImg, cv::Mat& _lableImg, int &iConnectedAreaCount) { //拓寬1個(gè)像素的原因是:如果連通域在邊緣,運(yùn)行此函數(shù)會(huì)異常崩潰,所以需要在周圍加一圈0值,確保連通域不在邊上 //==========圖像周圍拓寬1個(gè)像素============================================ int top, bottom; //【添加邊界后的圖像尺寸】 int leftImage, rightImage; int borderType = BORDER_CONSTANT; //BORDER_REPLICATE //【初始化參數(shù)】 top = (int)(1); bottom = (int)(1); leftImage = (int)(1); rightImage = (int)(1); Mat _binImg2, _binImg3; _binImg.copyTo(_binImg2); //初始化參數(shù)value Scalar value(0); //填充值 //創(chuàng)建圖像邊界 copyMakeBorder(_binImg2, _binImg3, top, bottom, leftImage, rightImage, borderType, value); //==========圖像周圍拓寬1個(gè)像素============================================ // 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); //取一行數(shù)據(jù) for (int j = 1; j < cols - 1; j++) { if (data[j] == 1) //像素不為0 { std::stack<std::pair<int, int>> neighborPixels; //新建一個(gè)棧 neighborPixels.push(std::pair<int, int>(i, j)); // 像素坐標(biāo): <i,j> ,以該像素為起點(diǎn),尋找連通域 ++label; // 開始一個(gè)新標(biāo)簽,各連通域區(qū)別的標(biāo)志 while (!neighborPixels.empty()) { // 獲取堆棧中的頂部像素并使用相同的標(biāo)簽對(duì)其進(jìn)行標(biāo)記 std::pair<int, int> curPixel = neighborPixels.top(); int curX = curPixel.first; int curY = curPixel.second; _lableImg.at<int>(curX, curY) = label; //對(duì)圖像對(duì)應(yīng)位置的點(diǎn)進(jìn)行標(biāo)記 // 彈出頂部像素 (頂部像素出棧) neighborPixels.pop(); // 加入8鄰域點(diǎn) if (_lableImg.at<int>(curX, curY - 1) == 1) {// 左點(diǎn) neighborPixels.push(std::pair<int, int>(curX, curY - 1)); //左邊點(diǎn)入棧 } if (_lableImg.at<int>(curX, curY + 1) == 1) {// 右點(diǎn) neighborPixels.push(std::pair<int, int>(curX, curY + 1)); //右邊點(diǎn)入棧 } if (_lableImg.at<int>(curX - 1, curY) == 1) {// 上點(diǎn) neighborPixels.push(std::pair<int, int>(curX - 1, curY)); //上邊點(diǎn)入棧 } if (_lableImg.at<int>(curX + 1, curY) == 1) {// 下點(diǎn) neighborPixels.push(std::pair<int, int>(curX + 1, curY)); //下邊點(diǎn)入棧 } //===============補(bǔ)充到8連通域====================================================== if (_lableImg.at<int>(curX - 1, curY - 1) == 1) {// 左上點(diǎn) neighborPixels.push(std::pair<int, int>(curX - 1, curY - 1)); //左上點(diǎn)入棧 } if (_lableImg.at<int>(curX - 1, curY + 1) == 1) {// 右上點(diǎn) neighborPixels.push(std::pair<int, int>(curX - 1, curY + 1)); //右上點(diǎn)入棧 } if (_lableImg.at<int>(curX + 1, curY - 1) == 1) {// 左下點(diǎn) neighborPixels.push(std::pair<int, int>(curX + 1, curY - 1)); //左下點(diǎn)入棧 } if (_lableImg.at<int>(curX + 1, curY + 1) == 1) {// 右下點(diǎn) neighborPixels.push(std::pair<int, int>(curX + 1, curY + 1)); //右下點(diǎn)入棧 } //===============補(bǔ)充到8連通域====================================================== } } } } iConnectedAreaCount = label - 1; //因?yàn)閘abel從2開始計(jì)數(shù)的 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(); //根據(jù)不同標(biāo)志位產(chǎn)生隨機(jī)顏色 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; } //#############添加顏色################################## //########調(diào)用########################################## Mat binImage = cv::imread("D:\\sxl\\處理圖片\\testImages\\22.jpg", 0); threshold(binImage, binImage, 50, 1, CV_THRESH_BINARY_INV); // 連通域標(biāo)記 Mat labelImg; int iConnectedAreaCount = 0; //連通域個(gè)數(shù) ConnectedCountBySeedFill(binImage, labelImg, iConnectedAreaCount);//針對(duì)黑底白字 int a=iConnectedAreaCount; // 顯示結(jié)果 Mat dstColor2=PaintColor(labelImg,iConnectedAreaCount); imshow("colorImg", dstColor2); Mat grayImg; labelImg *= 10; labelImg.convertTo(grayImg, CV_8UC1); imshow("labelImg", grayImg); waitKey(0); //########調(diào)用##########################################
補(bǔ)充知識(shí):Opencv快速獲取連通域
對(duì)于ndarray數(shù)據(jù)中的連通域查找,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()函數(shù)返回查找到的連通域個(gè)數(shù)和對(duì)應(yīng)的label。
上面代碼返回連通域個(gè)數(shù)為4(包含值為0區(qū)域,可通過lables過濾), labels結(jié)果如圖所示:
以上這篇使用OpenCV獲取圖片連通域數(shù)量,并用不同顏色標(biāo)記函就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python Tornado事件循環(huán)示例源碼解析
這篇文章主要為大家介紹了python Tornado事件循環(huán)示例源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09python爬蟲 基于requests模塊發(fā)起ajax的get請(qǐng)求實(shí)現(xiàn)解析
這篇文章主要介紹了python爬蟲 基于requests模塊發(fā)起ajax的get請(qǐng)求實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08在Python的Django框架中顯示對(duì)象子集的方法
這篇文章主要介紹了在Python的Django框架中顯示對(duì)象子集的方法,即queryset的參數(shù)的使用相關(guān),需要的朋友可以參考下2015-07-07如何取消pyecharts繪制地圖時(shí)默認(rèn)顯示小圓點(diǎn)標(biāo)識(shí)
這篇文章主要介紹了如何取消pyecharts繪制地圖時(shí)默認(rèn)顯示小圓點(diǎn)標(biāo)識(shí),文章內(nèi)容介紹詳細(xì)具有一定的參考價(jià)值?需要的小伙伴可以參考一下2022-04-04VSCode基礎(chǔ)使用與VSCode調(diào)試python程序入門的圖文教程
這篇文章主要介紹了VSCode基礎(chǔ)使用+VSCode調(diào)試python程序入門圖文教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03搭建pypi私有倉(cāng)庫(kù)實(shí)現(xiàn)過程詳解
這篇文章主要介紹了搭建pypi私有倉(cāng)庫(kù)實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Keras搭建分類網(wǎng)絡(luò)平臺(tái)VGG16?MobileNet?ResNet50
這篇文章主要為大家介紹了Keras搭建分類網(wǎng)絡(luò)平臺(tái)VGG16?MobileNet?ResNet50,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05詳解Python 中sys.stdin.readline()的用法
這篇文章主要介紹了Python 中sys.stdin.readline()的用法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09