机器视觉作业--目标检测

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);
}

 效果图:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值