天天看点

opencv 多圆查找

测试图片

opencv 多圆查找
bool MainWindow::findAllContours()
{
    cv::Mat filteredImg;
    cv::Mat binariedImg;
    //    cv::Mat destImg;
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    fileName = QFileDialog::getOpenFileName(NULL,"open image","F://testImageGray//1//","*.jpg");
    if(fileName.size () > 5){
        image = imread(fileName.toStdString (), 0);
        cv::Mat oriImg(INPUT_VIDEO_H,INPUT_VIDEO_W,CV_8UC1,image.data);

        //do image filter
        cv::blur(oriImg,filteredImg,Size(7,7),Point(-1,-1));

        //Binarization process of the cropped image
        cv::adaptiveThreshold(filteredImg, binariedImg,255.0, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 27, -25);

        //start to find split rect after Binarization
        cv::Mat imgTemp = binariedImg.clone();
        //查找轮廓
        cv::findContours(imgTemp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0,0));
        qDebug() << "contours.size() = " << contours.size();
        int max_w = 0;
        Rect recordMaxPoint;//记录最大圆心位置
        for (int i = 0; i < contours.size(); i++)
        {
            vector<Point> edgePoint = contours.at(i);
            Rect rect = cv::boundingRect(edgePoint);//求区域
            if(rect.width > max_w)
            {
                max_w = rect.width;//求最大面积
                recordMaxPoint = rect;
            }
        }

        for (int i = 0; i < contours.size(); i++) {
            vector<Point> edgePoint = contours.at(i);
            Rect rect = cv::boundingRect(edgePoint);//求区域
            qDebug() << QString("x = %1,y = %2,width = %3, height = %4").arg(rect.x).arg(rect.y).arg(rect.width).arg(rect.height);//打印位置高宽
            //画圆

            if(rect.width > max_w/2){//过滤错误小圆
                cv::circle(image, // 目标图像
                           cv::Point(rect.x + rect.width/2,rect.y + rect.height/2), // 中心点坐标
                           rect.height/2+5, // 半径
                           50, // 颜色(这里用黑色)
                           2); // 厚
            }
        }
    }
//    namedWindow("result", 1);
//    imshow("result", image);
    QImage resultImage = cvMat2QImage(image);
    QImage newImg  =  resultImage.scaled(ui->original_label->width(), ui->original_label->height(),Qt::KeepAspectRatioByExpanding);
    ui->original_label->setPixmap(QPixmap::fromImage(newImg));
    return 0;
}