1,硬币检测
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("D:\\C++\\coin.png", 0);
if (img.empty())
{
cout << "Could not open or find the image!\n";
return -1;
}
Mat coin2;
threshold(img,coin2,86,255,THRESH_BINARY);
Mat connect_coin, stats, centroids;
connect_coin = Mat::zeros(img.size(),CV_32S);
int Num = connectedComponentsWithStats(coin2,connect_coin,stats,centroids,8,CV_32S);
for (int i = 1; i < Num; i++)
{
cout << " connectedComponents NO." << i << endl;
Rect bandbox;
bandbox.x = stats.at<int>(i,0);
bandbox.y = stats.at<int>(i, 1);
bandbox.width = stats.at<int>(i, 2);
bandbox.height = stats.at<int>(i, 3);
rectangle(img,bandbox,Scalar(255,255,255),1,8,0);
rectangle(coin2, bandbox, Scalar(255, 255, 255), 1, 8, 0);
}
imshow("img",img);
imshow("coin2",coin2);
waitKey(0);
return 0;
}
效果:
2,焊点检测
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("D:\\C++\\handian.jpg", 0);
if (img.empty())
{
cout << "Could not open or find the image!\n";
return -1;
}
img = 255 - img;
Mat cut_two, cut_erode, cut_dilate, label, stats, centroids;
threshold(img,cut_two,0,255,THRESH_OTSU);
/
Mat element = getStructuringElement(MORPH_RECT,Size(5,5));
erode(cut_two,cut_erode,element,Point(-1,-1),2);
dilate(cut_erode, cut_dilate, element, Point(-1, -1),2);
int Num = connectedComponentsWithStats(cut_erode,label,stats,centroids,8,CV_32S);
cout << "点的个数" << Num-1 << endl;
imshow("cut_erode",cut_erode);
imshow("cut_dilate",cut_dilate);
waitKey(0);
return 0;
}
效果图:
3,回形针检测,计数
代码:实现原理很简单就是根据连通域的面积给的阈值
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
int Num=0;
Mat src = imread("D:\\C++\\hui.png", 0);
Mat src_gray,labels,stats,centroids;
threshold(src,src_gray,0,255,THRESH_OTSU);
src_gray = 255 - src_gray;
imshow("src_gray",src_gray);
connectedComponentsWithStats(src_gray,labels,stats,centroids,8,CV_32S);
for (int i = 0; i < stats.rows; i++)
{
if (stats.at<int>(i, 4) >= 4000 && stats.at<int>(i, 4) <= 8000)
{
Num = Num + 1;
cv::Rect rect;
rect.x = stats.at<int>(i, 0);
rect.y = stats.at<int>(i, 1);
rect.width = stats.at<int>(i, 2);
rect.height = stats.at<int>(i, 3);
rectangle(src_gray, rect, CV_RGB(255, 255, 255), 1, 8, 0);
}
}
std::cout << "回形针个数:" << Num<< std::endl;
imshow("src_gray", src_gray);
waitKey(0);
}
效果图: