溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

opencv3.0識(shí)別并提取圖形中的矩形的方法是什么

發(fā)布時(shí)間:2021-12-15 18:32:21 來(lái)源:億速云 閱讀:190 作者:柒染 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)opencv3.0識(shí)別并提取圖形中的矩形的方法是什么,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

利用opencv來(lái)識(shí)別圖片中的矩形。

其中遇到的問(wèn)題主要是識(shí)別輪廓時(shí)矩形內(nèi)部的形狀導(dǎo)致輪廓不閉合。

1. 對(duì)輸入灰度圖片進(jìn)行高斯濾波2. 做灰度直方圖,提取閾值,做二值化處理3. 提取圖片輪廓4. 識(shí)別圖片中的矩形5. 提取圖片中的矩形

1.對(duì)輸入灰度圖片進(jìn)行高斯濾波

cv::Mat src = cv::imread("F:\\t13.bmp",CV_BGR2GRAY);  cv::Mat hsv;  GaussianBlur(src,hsv,cv::Size(5,5),0,0);

2.做灰度直方圖,提取閾值,做二值化處理

由于給定圖片,背景是黑色,矩形背景色為灰色,矩形中有些其他形狀為白色,可以參考為:提取輪廓時(shí),矩形外部輪廓并未閉合。因此,我們需要對(duì)整幅圖做灰度直方圖,找到閾值,進(jìn)行二值化

處理。即令像素值(黑色)小于閾值的,設(shè)置為0(純黑色);令像素值(灰色和白色)大于閾值的,設(shè)

置為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.提取圖片輪廓

為了識(shí)別圖片中的矩形,在識(shí)別之前還需要提取圖片的輪廓。在經(jīng)過(guò)濾波、二值化處理后,輪廓提取后的效果比未提取前的效果要好很多。

4.識(shí)別矩形

識(shí)別矩形的條件為:圖片中識(shí)別的輪廓是一個(gè)凸邊形、有四個(gè)頂角、所有頂角的角度都為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);

   } }

關(guān)于opencv3.0識(shí)別并提取圖形中的矩形的方法是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI