// // Created by leoxae on 19-8-14. // 卡片区域分割 // #include "CardRegionSegmentation.h" /** * funcName 卡片区域分割 * @param width * @param height * @param cols * @param rows * @return rects 卡片集合 */ map<int, CardPosition> CardRegionSegmentation::createCardsRect(Mat img, int cols, int rows) { int width = img.cols; int height = img.rows; int w = width / cols, h = height / rows; map<int, CardPosition> rects; int idx = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { CardPosition cp; cp.idx = (idx++); cp.rect = Rect(w * j, h * i, w, h); cp.center = Point2f(j * w + w / 2, i * h + h / 2); rects[idx] = cp; } } return rects; } /** * 构建最外围区域,去掉重复的卡片 * @param rects * @return * 还可以在优化,该算法对重叠卡片过滤不掉 */ vector<Rect> CardRegionSegmentation::conutersOrder(vector<Rect> rects) { int idx = 0; const int size = rects.size(); Rect temp; vector<Rect> temp_rects = rects; for (;;) { temp = temp_rects[idx]; vector<Rect> rms; for (Rect &r: rects) { int max_w = r.x + r.width; int max_h = r.y + r.height; if (r.y >= temp.y && r.y < temp.y + temp.height && max_h >= temp.y && max_h < temp.y + temp.height) { if (r.x >= temp.x && r.x < temp.x + temp.width && max_w >= temp.x && max_w < temp.x + temp.width) { if (temp != r) { if (find(rects.begin(), rects.end(), r) != rects.end()) { rms.push_back(r); } } } } } rects = TempHelper::removeAll(rects, rms); idx++; if (idx >= size) { break; } } return rects; }
// // Created by leoxae on 19-8-14. // #ifndef KEEKOAIROBOT_CARDREGIONSEGMENTATION_H #define KEEKOAIROBOT_CARDREGIONSEGMENTATION_H #include "../../globals.h" #include "../../core/math/PlaneGeometry.h" class CardRegionSegmentation{ public: /** * funcName 卡片区域分割 * @param width * @param height * @param cols * @param rows * @return rects 卡片集合 */ static map<int, CardPosition> createCardsRect(Mat img, int cols, int rows); /** * 去重 * @param rects * @return */ static vector<Rect> conutersOrder(vector<Rect> rects) ; }; #endif //KEEKOAIROBOT_CARDREGIONSEGMENTATION_H
void RegionSegmentation(){ string path = "/home/leoxae/KeekoRobot/TestPic/33.jpg"; Mat src = imread(path); int width = src.cols; int hight = src.rows; int cols = 8; int rows = 3; CardRegionSegmentation::createCardsRect(src,cols,rows); waitKey(0); }