[英]Detect bounding box in 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;
}
}
}
}`
這是我的形象:
您沒有得到理想的結果,因為您正在尋找幾乎矩形的輪廓,但是由於您感興趣的輪廓不是矩形的,所以這將不起作用。 您可以看到(藍色)該輪廓的近似值(在我的二值化圖像上獲得):
這表明您這不是一個可靠的約束。
在這種情況下,您可以輕松解決此問題,為每個輪廓計算邊界框,並保持最大輪廓(綠色):
碼:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.