opencv3.0識別并提取圖形中的矩形的方法
利用opencv來識別圖片中的矩形。
其中遇到的問題主要是識別輪廓時矩形內部的形狀導致輪廓不閉合。
1. 對輸入灰度圖片進行高斯濾波
2. 做灰度直方圖,提取閾值,做二值化處理
3. 提取圖片輪廓
4. 識別圖片中的矩形
5. 提取圖片中的矩形
1.對輸入灰度圖片進行高斯濾波
cv::Mat src = cv::imread("F:\\t13.bmp",CV_BGR2GRAY);
cv::Mat hsv;
GaussianBlur(src,hsv,cv::Size(5,5),0,0);
2.做灰度直方圖,提取閾值,做二值化處理
由于給定圖片,背景是黑色,矩形背景色為灰色,矩形中有些其他形狀為白色,可以參考為:
提取輪廓時,矩形外部輪廓并未閉合。因此,我們需要對整幅圖做灰度直方圖,找到閾值,進行二值化
處理。即令像素值(黑色)小于閾值的,設置為0(純黑色);令像素值(灰色和白色)大于閾值的,設
置為255(白色)
// Quantize the gray scale to 30 levels
int gbins = 16;
int histSize[] = {gbins};
// gray scale varies from 0 to 256
float granges[] = {0,256};
const float* ranges[] = { granges };
cv::MatND hist;
// we compute the histogram from the 0-th and 1-st channels
int channels[] = {0};
//calculate hist
calcHist( &hsv, 1, channels, cv::Mat(), // do not use mask
hist, 1, histSize, ranges,
true, // the histogram is uniform
false );
//find the max value of hist
double maxVal=0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int scale = 20;
cv::Mat histImg;
histImg.create(500,gbins*scale,CV_8UC3);
//show gray scale of hist image
for(int g=0;g<gbins;g++){
float binVal = hist.at<float>(g,0);
int intensity = cvRound(binVal*255);
rectangle( histImg, cv::Point(g*scale,0),
cv::Point((g+1)*scale - 1,binVal/maxVal*400),
CV_RGB(0,0,0),
CV_FILLED );
}
cv::imshow("histImg",histImg);
//threshold processing
cv::Mat hsvRe;
threshold( hsv, hsvRe, 64, 255,cv::THRESH_BINARY);
3.提取圖片輪廓
為了識別圖片中的矩形,在識別之前還需要提取圖片的輪廓。在經過濾波、二值化處理后,輪廓提取后的效果比未提取前的效果要好很多。
4.識別矩形
識別矩形的條件為:圖片中識別的輪廓是一個凸邊形、有四個頂角、所有頂角的角度都為90度。
vector<Point> approx;
for (size_t i = 0; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), approx,
arcLength(Mat(contours[i]), true)*0.02, true);
if (approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for( int j = 2; j < 5; j++ )
{
double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
maxCosine = MAX(maxCosine, cosine);
}
if( maxCosine < 0.3 )
squares.push_back(approx);
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C++?LeetCode1769移動所有球到每個盒子最小操作數(shù)示例
這篇文章主要為大家介紹了C++?LeetCode1769移動所有球到每個盒子所需最小操作數(shù)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12

