opencv-010-图像像素值统计及应用(普通图像转化为二值图像)

知识点

  • 最小(min)
  • 最大(max)
  • 均值(mean)
  • 标准方差(standard deviation)

API知识点

  • 最大最小值minMaxLoc
  • 计算均值与标准方差meanStdDev

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <opencv2/opencv.hpp>

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<double>(0, 0), stddev.at<double>(0, 0));
printf("green channel mean:%.2f, stddev: %.2f \n", mean.at<double>(1, 0), stddev.at<double>(1, 0));
printf("red channel mean:%.2f, stddev: %.2f \n", mean.at<double>(2, 0), stddev.at<double>(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<Vec3b>(row, col);
bgr[0] = bgr[0] < mean.at<double>(0, 0) ? 0 : 255;
bgr[1] = bgr[1] < mean.at<double>(1, 0) ? 0 : 255;
bgr[2] = bgr[2] < mean.at<double>(2, 0) ? 0 : 255;
src_bgr.at<Vec3b>(row, col) = bgr;
}
}
imshow("binary", src_bgr);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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()

结果

代码地址

github