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

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
fanfuhan OpenCV 教學010 ~ opencv-010-圖像像素值統計及應用(普通圖像轉化為二值化圖像)[將彩色圖的相似顏色都標成相同區域,簡易分割圖片方式] 資料來源: https://fanfuhan.github.io/ https://fanfuhan.github.io/2019/03/25/opencv-010/ GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV C++ #include #include using namespace std; using namespace cv; /* * 图像像素值统计及应用(普通图像转化为二值图像) */ int main() { Mat src_bgr = imread("../images/test.png"); Mat src_gray; cvtColor(src_bgr, src_gray, COLOR_BGR2GRAY); if (src_bgr.empty() || src_gray.empty()) { cout << "could not load image.." << endl; } imshow("input_bgr", src_bgr); // 计算灰度图像的最大最小值 double minVal, maxVal; Point minLoc, maxLoc; minMaxLoc(src_gray, &minVal, &maxVal, &minLoc, &maxLoc); cout << "paramenters of src_gray:" << endl; printf("min:%.2f, max:%.2f \n", minVal, maxVal); printf("min loc: (%d, %d) \n", minLoc.x, minLoc.y); printf("max loc: (%d, %d) \n", maxLoc.x, maxLoc.y); // 普通图像转二值图像 Mat mean, stddev; meanStdDev(src_bgr, mean, stddev); cout << "paramenters of src_bgr:" << endl; printf("blue channel mean:%.2f, stddev: %.2f \n", mean.at(0, 0), stddev.at(0, 0)); printf("green channel mean:%.2f, stddev: %.2f \n", mean.at(1, 0), stddev.at(1, 0)); printf("red channel mean:%.2f, stddev: %.2f \n", mean.at(2, 0), stddev.at(2, 0)); for (int row = 0; row < src_bgr.rows; ++row) { for (int col = 0; col < src_bgr.cols; ++col) { Vec3b bgr = src_bgr.at(row, col); bgr[0] = bgr[0] < mean.at(0, 0) ? 0 : 255; bgr[1] = bgr[1] < mean.at(1, 0) ? 0 : 255; bgr[2] = bgr[2] < mean.at(2, 0) ? 0 : 255; src_bgr.at(row, col) = bgr; } } imshow("binary", src_bgr); waitKey(0); return 0; } Python import cv2 as cv import numpy as np src = cv.imread("../images/test.png", cv.IMREAD_GRAYSCALE) cv.namedWindow("input", cv.WINDOW_AUTOSIZE) cv.imshow("input", src) min, max, minLoc, maxLoc = cv.minMaxLoc(src) print("min: %.2f, max: %.2f"% (min, max)) print("min loc: ", minLoc) print("max loc: ", maxLoc) means, stddev = cv.meanStdDev(src) print("mean: %.2f, stddev: %.2f"% (means, stddev)) src[np.where(src < means)] = 0 src[np.where(src > means)] = 255 cv.imshow("binary", src) cv.waitKey(0) cv.destroyAllWindows()

本文由jashliaoeuwordpress提供 原文連結

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