- 用途:统计直方图;求取图像像素最大值、最小值,对图像进行归一化;求取图像均值、方差,进行分割或归一化;根据方差判断图像中信息量多少(若方差很小则说明图像像素间差异小,有效信息少);
- 两个API:
- minMaxLoc:可用于模板匹配,找到匹配的点在哪里。
- meanStdDev:对于一些图像,若方差比较小,则图像携带的信息量少。
- 根据图像均值进行二值化
根据图像均值对灰度图像进行二值化/分割
C++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, const char *argv[])
{
Mat src = imread("D:/vcprojects/images/test.png", IMREAD_GRAYSCALE);
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
double minVal; double maxVal; Point minLoc; Point maxLoc; // 先定义
minMaxLoc(src, &minVal, &maxVal, &minLoc, &maxLoc, Mat()); // 通过引用对变量写入值
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);
// 彩色图像 三通道的 均值与方差
src = imread("D:/vcprojects/images/test.png");
Mat means, stddev; // 均值和方差不是一个值。对彩色图像是三行一列的mat
meanStdDev(src, means, stddev);
printf("blue channel->> mean: %.2f, stddev: %.2f\n", means.at<double>(0, 0), stddev.at<double>(0, 0));
printf("green channel->> mean: %.2f, stddev: %.2f\n", means.at<double>(1, 0), stddev.at<double>(1, 0));
printf("red channel->> mean: %.2f, stddev: %.2f\n", means.at<double>(2, 0), stddev.at<double>(2, 0));
waitKey(0);
return 0;
}
Python
import cv2 as cv
import numpy as np
src = cv.imread("D:/vcprojects/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()
网友评论