opencv学习之米粒分割 #201906121549

include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main(){

Mat pic =imread("/Users/leung/Documents/imgs/Rice.png");
Mat gray,bw;
cvtColor(pic, gray, COLOR_BGR2GRAY);
threshold(gray, bw, 0, 255, THRESH_OTSU);

Mat seg = bw.clone();

//cnts 二维点集合
vector<vector<Point>> cnts;
//将米粒轮廓集合放入cnts
findContours(seg,cnts, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

drawContours(pic, cnts, -1, Scalar(0,0,0xff));
    

float area;
Rect rect;

// count为有效米粒的个数
int count = 0;

string strCount;
for(int i = 0; i<=cnts.size() - 1; i++){
    
    // c 为每一个米粒轮廓
    vector<Point> c =cnts[i];
    area = contourArea(c);
    if(area < 10)
        continue;
    count++;
    cout << "blob" << i << ":" << area << endl;
    //每一个米粒的外接矩形
    rect = boundingRect(c);
    
    //将外接矩形画在原图上
    rectangle(pic, rect, Scalar(0xff,0xff,0xff), 1);
    
    stringstream ss;
    ss << count;
    ss >> strCount;
    putText(pic, strCount, Point(rect.x, rect.y), FONT_HERSHEY_PLAIN, 0.5, Scalar(0, 0xff, 0));
}

imshow("gray", pic);
//imshow("bw", bw);
waitKey();

}

posted on 2019-06-12 15:50  Leung_ss  阅读(413)  评论(0编辑  收藏  举报

导航