> 文章列表 > 机器视觉技术分享-Blob分析 含C++ ,python代码说明

机器视觉技术分享-Blob分析 含C++ ,python代码说明

机器视觉技术分享-Blob分析 含C++ ,python代码说明

在数字图像处理中,Blob分析是一种基于连通性的图像分析方法,用于检测和分析图像中的连通区域。Blob分析可以用于许多应用,例如目标检测、形状识别、运动跟踪等。

在Blob分析中,一个连通区域被称为一个Blob,它可以由一组相邻的像素组成。Blob的特征通常包括面积、周长、重心、最小外接矩形等。Blob分析的基本步骤包括二值化、连通性分析和特征提取等。

以下是使用C++和OpenCV库实现Blob分析的代码示例:

#include <opencv2/opencv.hpp>
#include <iostream>using namespace cv;
using namespace std;int main()
{// 读取图像Mat img = imread("blob.jpg", IMREAD_GRAYSCALE);// 二值化Mat thresh;threshold(img, thresh, 127, 255, THRESH_BINARY);// 连通性分析Mat labels, stats, centroids;int num_labels = connectedComponentsWithStats(thresh, labels, stats, centroids);// 特征提取for (int i = 1; i < num_labels; i++) {int area = stats.at<int>(i, CC_STAT_AREA);int x = stats.at<int>(i, CC_STAT_LEFT);int y = stats.at<int>(i, CC_STAT_TOP);int w = stats.at<int>(i, CC_STAT_WIDTH);int h = stats.at<int>(i, CC_STAT_HEIGHT);double cx = centroids.at<double>(i, 0);double cy = centroids.at<double>(i, 1);cout << "Blob " << i << ": area=" << area << ", position=(" << cx << ", " << cy << "), size=(" << w << ", " << h << ")" << endl;rectangle(img, Point(x, y), Point(x + w, y + h), Scalar(255, 0, 0), 2);}// 显示结果imshow("Blob Analysis", img);waitKey(0);return 0;
}

 以下是使用Python和OpenCV库实现Blob分析的代码示例:

import cv2# 读取图像
img = cv2.imread('blob.jpg', cv2.IMREAD_GRAYSCALE)# 二值化
thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]# 连通性分析
connectivity = 8
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)# 特征提取
for i in range(1, num_labels):area = stats[i, cv2.CC_STAT_AREA]x, y, w, h = stats[i, cv2.CC_STAT_LEFT], stats[i, cv2.CC_STAT_TOP], stats[i, cv2.CC_STAT_WIDTH], stats[i, cv2.CC_STAT_HEIGHT]cx, cy = centroids[i]print(f'Blob {i}: area={area}, position=({cx}, {cy}), size=({w}, {h})')cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)# 显示结果
cv2.imshow('Blob Analysis', img)
cv2.waitKey(0)
cv2.destroyAllWindows()