背景:在我們生活中常常需要我們用肉眼來計算某些物品的數量,如果通過人工操作會產生:①.效率低下;②.長時間的作業會導致眼睛疲勞導致錯誤的計算;為此,我們可以使用影像處理來檢測方便我們.
代碼如下:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
Mat srcImage; //源圖
Mat dstImage; //目標圖
Mat grayImage;//灰度圖
int Coin = 0; //硬幣個數
string intToString(int number)
{
ostringstream ss;
ss << number;
return ss.str();
}
int main()
{
//載圖
srcImage = imread("D:/photoes/coin.png");
if (srcImage.empty())
{
cout << "fail to read the Image!" << endl;
return -1;
}
//色彩空間轉換
cvtColor(srcImage, grayImage,COLOR_BGR2GRAY);
//平滑濾波降噪
blur(grayImage, dstImage,Size(3,3));
// imshow("平滑降噪",dstImage);
//使用大津法閾值分割前景與背景
threshold(dstImage,dstImage,0,255,THRESH_OTSU);
// imshow("閾值分割",dstImage);
//孔洞填充
//floodFill(dstImage,Point(0,0),Scalar(255));
//imshow("空洞填充",dstImage);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(dstImage,contours,hierarchy,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
vector<vector<Point>> contours_poly(contours.size());
for (int i = 0; i < contours.size(); i++)
{
approxPolyDP(contours[i], contours_poly[i], 3, true);
//drawContours(dstImage, contours_poly, i, Scalar(255));
Point2f center;
float radius;
minEnclosingCircle(contours_poly[i], center, radius);
if (radius < 20)
continue;
circle(dstImage,center,radius,Scalar(255),4);
circle(srcImage, center, radius, Scalar(0,0,255), 1);
Coin++;
}
//imshow("找輪廓填輪廓",dstImage);
string text = "detected coin's number:" + intToString(Coin);
int fontFace = FONT_HERSHEY_COMPLEX;
double fontScale = 1;
int thickness = 1;
Size textSize = getTextSize(text, fontFace, fontScale, thickness, 0);
Point org = Point(0, textSize.height);
putText(srcImage, text, org, fontFace, fontScale, Scalar(0,0,255), 1, 8);
imshow("原始圖", srcImage);
waitKey(0);
}
效果圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/291407.html
標籤:AI
上一篇:HCNA Routing&Switching之二層交換技術VLAN基礎
下一篇:機器學習課后題——支持向量機
