2016-01-14 127 views
0

我有一個圖像,我獲得了它的二進制圖像。我期望一個矩形的邊界框,但我沒有得到它。這是我的代碼:檢測OCR中的邊界框?

vector<vector<Point>> contours; 
Vec4i hierarchy; 
findContours(binary, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); 
/*Mat drawing = Mat::zeros(binary.size(), CV_8UC3); 
for (int i = 0; i < contours.size(); i++) 
{ 
    Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); 
    drawContours(drawing, contours, i, color, 1, 8, hierarchy, 0, Point()); 
} 
imshow("contours", drawing);*/ 

vector<Point> approx, approxRectangle; 
Rect bounding_rect(0, 0, 0, 0); 
double max_area = 0; 
for (int i = 0; i < contours.size(); i++)// xet tung contour 
{ 
    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); 

    if (approx.size() == 4 && isContourConvex(Mat(approx))) 
    { 
     Rect box = boundingRect(contours[i]); 
     if (bounding_rect.area() == 0){ 
      bounding_rect = box; 
      approxRectangle = approx; 
     } 
     else{ 
      if (bounding_rect.area() < box.area()){ 
       bounding_rect = box; 
       approxRectangle = approx; 
      } 
     } 
    } 
}` 

這是我的形象:

回答

2

你沒有得到想要的結果,因爲你正在尋找幾乎矩形輪廓,但韓元因爲你感興趣的輪廓不是矩形,所以不起作用。你可以看到(藍色),其輪廓(在我的二值化圖像獲得)的近似值:

enter image description here

這說明你,這是不是一個可靠的約束。

您可以輕鬆地解決這個問題,在這種情況下,計算每個輪廓的邊框,並保持最大的(綠色):

enter image description here

代碼:

#include <opencv2/opencv.hpp> 
#include <iostream> 
#include <algorithm> 
using namespace std; 
using namespace cv; 

int main() 
{ 
    // Load image 
    Mat3b img = imread("path_to_image"); 

    // Convert to grayscale 
    Mat1b binary; 
    cvtColor(img, binary, COLOR_BGR2GRAY); 

    // Binarize (remove anti-aliasing artifacts) 
    binary = binary > 200; 

    // Find contours 
    vector<vector<Point>> contours; 
    findContours(binary.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0)); 

    // Compute the bounding boxes 
    vector<Rect> boxes; 
    for (int i = 0; i < contours.size(); ++i) 
    { 
     boxes.push_back(boundingRect(contours[i])); 
    } 

    // Find index of largest contours 
    int idx_largest_box = distance(boxes.begin(), max_element(boxes.begin(), boxes.end(), [](const Rect& lhs, const Rect& rhs) { 
     return lhs.area() < rhs.area(); 
    })); 

    // Draw largest box 
    rectangle(img, boxes[idx_largest_box], Scalar(0,255,0)); 

    imshow("Result", img); 
    waitKey(); 

    return 0; 
} 
+0

我試着這條路。但有些情況下,圖像是歪斜的。我想檢測4個角點並使用它來旋轉。你有什麼建議嗎? –

+0

查找最大的斑點,並使用minAreaRect – Miki

+0

或者簡單地將此代碼更改爲使用RotatedRect而不是Rect,使用minAreaRect更改boundingRect。其餘的應該是相同的(除了繪圖結果) – Miki