3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
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提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦