search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

fanfuhan OpenCV 教學046 ~ opencv-046-二值化圖像&聯通元件標記/尋找/計算(計數)[八方鍊碼] – jashliao部落格

fanfuhan OpenCV 教學046 ~ opencv-046-二值圖像&聯通元件標記/尋找/計算(計數)[八方鍊碼]

資料來源: https://fanfuhan.github.io/

https://fanfuhan.github.io/2019/04/14/opencv-046/

GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV

C++

#include 
#include 

using namespace std;
using namespace cv;

RNG rng(12345);

void connected_component_demo(Mat &image);

/*
 * 二值图像的连通组件标记
 */
int main() {
    Mat src = imread("../images/rice.png");
    if (src.empty()) {
        cout << "could not load image.." << endl;
    }
    imshow("input", src);

    connected_component_demo(src);

    waitKey(0);
    return 0;
}

void connected_component_demo(Mat &image) {
    // extract labels
    Mat gray, binary;
    GaussianBlur(image, image, Size(3, 3), 0);
    cvtColor(image, gray, COLOR_BGR2GRAY);
    threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
    Mat labels = Mat::zeros(image.size(), CV_32S);
    int num_labels = connectedComponents(binary, labels, 8, CV_32S);
    cout << "total labels : " << num_labels - 1 << endl;
    vector colors(num_labels);

    // 背景颜色
    colors[0] = Vec3b(0, 0, 0);

    // 目标颜色
    for (int i = 1; i < num_labels; ++i) {
        colors[i] = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
    }

    // 给结果着色
    Mat dst = Mat::zeros(image.size(), image.type());
    for (int row = 0; row < image.rows; ++row) {
        for (int col = 0; col < image.cols; ++col) {
            int label = labels.at(row, col);
            if (label == 0) continue;
            dst.at(row, col) = colors[label];
        }
    }

    imshow("result", dst);
}

Python

import cv2 as cv
import numpy as np


def connected_components_demo(src):
    src = cv.GaussianBlur(src, (3, 3), 0)
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    cv.imshow("binary", binary)

    output = cv.connectedComponents(binary, connectivity=8, ltype=cv.CV_32S)
    num_labels = output[0]
    labels = output[1]
    colors = []
    for i in range(num_labels):
        b = np.random.randint(0, 256)
        g = np.random.randint(0, 256)
        r = np.random.randint(0, 256)
        colors.append((b, g, r))

    colors[0] = (0, 0, 0)
    h, w = gray.shape
    image = np.zeros((h, w, 3), dtype=np.uint8)
    for row in range(h):
        for col in range(w):
            image[row, col] = colors[labels[row, col]]

    cv.imshow("colored labels", image)
    cv.imwrite("D:/labels.png", image)
    print("total rice : ", num_labels - 1)


src = cv.imread("D:/images/rice.png")
h, w = src.shape[:2]
connected_components_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()


熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦