案例二 圖像分割

基于連通域的圖像分割案例

可以用于物體計數(shù)和區(qū)域分割
碼上 后期進(jìn)行更改優(yōu)化

#include <opencv2/core/utility.hpp>
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
 
using namespace cv;
using namespace std;
 
Mat img;
int threshval = 100;
 
static void on_trackbar(int, void*)
{
    Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
    Mat labelImage(img.size(), CV_32S);
    int nLabels = connectedComponents(bw, labelImage, 8);
    std::vector<Vec3b> colors(nLabels);
    colors[0] = Vec3b(0, 0, 0);//background
    for (int label = 1; label < nLabels; ++label) {
        colors[label] = Vec3b((rand() & 255), (rand() & 255), (rand() & 255));
    }
    Mat dst(img.size(), CV_8UC3);
    for (int r = 0; r < dst.rows; ++r) {
        for (int c = 0; c < dst.cols; ++c) {
            int label = labelImage.at<int>(r, c);
            Vec3b &pixel = dst.at<Vec3b>(r, c);
            pixel = colors[label];
        }
    }
 
    imshow("Connected Components", dst);
}
 
static void help()
{
    cout << "\n This program demonstrates connected components and use of the trackbar\n"
        "Usage: \n"
        "  ./connected_components <image(../data/stuff.jpg as default)>\n"
        "The image is converted to grayscale and displayed, another image has a trackbar\n"
        "that controls thresholding and thereby the extracted contours which are drawn in color\n";
}
 
const char* keys =
{
    "{help h||}{@image|../data/stuff.jpg|image for converting to a grayscale}"
};
 
int main(int argc, const char** argv)
{
    CommandLineParser parser(argc, argv, keys);
    if (parser.has("help"))
    {
        help();
        return 0;
    }
    string inputImage = parser.get<string>(0);
    //img = imread(inputImage.c_str(), 0);
    img = imread("1.png", 0);
    if (img.empty())
    {
        cout << "Could not read input image file: " << inputImage << endl;
        return -1;
    }
 
    namedWindow("Image", 1);
    imshow("Image", img);
 
    namedWindow("Connected Components", 1);
    createTrackbar("Threshold", "Connected Components", &threshval, 255, on_trackbar);
    on_trackbar(threshval, 0);
 
    waitKey(0);
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容