#include <iostream>
#include <iomanip>
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
using namespace std;
static Scalar randomColor(RNG& rng)
{
int icolor = (unsigned)rng;
return Scalar(icolor & 255, (icolor >> 8) & 255, (icolor >> 16) & 255);
}
void ConnectCompents(Mat img) {
Mat labels;//0爲背景
auto num_objects = connectedComponents(img, labels);
if (num_objects < 2) {
cout << "無對象" << endl;
}
else {
cout << "找到的物體個數" << num_objects - 1 << endl;
}
Mat output = Mat::zeros(img.rows, img.cols, CV_8UC3);
RNG rng(0xFFFFFFFF);
for (int i = 1; i < num_objects; i++) {
Mat mask = labels == i;
output.setTo(randomColor(rng), mask);
}
imshow("result", output);
}
void ConnectCompentStatus(Mat img) {
Mat labels,status,centroids;//0爲背景
auto num_objects = connectedComponentsWithStats(img,labels,status,centroids);
if (num_objects < 2) {
cout << "無對象" << endl;
}
else {
cout << "找到的物體個數" << num_objects - 1 << endl;
}
Mat output = Mat::zeros(img.rows, img.cols, CV_8UC3);
RNG rng(0xFFFFFFFF);
for (int i = 1; i < num_objects; i++) {
Mat mask = labels == i;
output.setTo(randomColor(rng), mask);
stringstream ss;
ss << "area:" << status.at<int>(i, CC_STAT_AREA);
putText(output, ss.str(), centroids.at<Point2d>(i), FONT_HERSHEY_SCRIPT_SIMPLEX, 0.4, Scalar(255,255,255));
}
imshow("result", output);
}
int FindContoursBasic(Mat img)
{
vector<vector<Point> > contours;//點集數組.那個空格必須有,不然會被讀成>>。
findContours(img, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat output = Mat::zeros(img.rows, img.cols, CV_8UC3);//定義繪製板
if (contours.size() == 0)
{
cout << "No objects founded" << endl;
return -1;
}
else
{
cout << "objects number:" << contours.size() << endl;
}
RNG rng(0xFFFFFFFF);//隨機數
for (int i = 0; i < contours.size(); i++)
{
drawContours(output, contours, i, randomColor(rng));//依次將輪廓繪製到output上
}
imshow("Output", output);
}
int main(){
Mat image1 = imread("工件圖.jpg");
Mat image2 = imread("背景.jpg", 0);
if((image1.data == NULL) || (image2.data==NULL) ){
cout << "讀圖失敗" << endl;
return 0;
}
Mat grayimage,blurimage,image3;
cvtColor(image1, grayimage, COLOR_RGB2GRAY);
//imshow("srcimage", grayimage);
// 中值濾波
medianBlur(grayimage, blurimage, 13);
//imshow("blurimage", blurimage);
//除去背景
Mat img32, patten32;
blurimage.convertTo(img32, CV_32F);
resize(image2, image2, Size(blurimage.cols, blurimage.rows));
image2.convertTo(patten32, CV_32F);
image3 = 1 - (img32 / patten32);
image3.convertTo(image3, CV_8U, 255);
//imshow("去除背景", image3);
/*//創建光模式
Mat pattern;
blur(grayimage, pattern, Size(grayimage.cols / 3, grayimage.cols / 3));
imshow("背景", pattern);*/
//二值化
Mat imgbw;
threshold(image3, imgbw, 30,255,THRESH_BINARY);
imshow("二值化", imgbw);
//找輪廓
//ConnectCompentStatus(imgbw);
FindContoursBasic(imgbw);
waitKey();
return 0;
}
opencv查找連通分量和輪廓
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.