010 图像像素值统计

2019-08-11  本文已影响0人  几时见得清梦
  1. 根据图像均值进行二值化
根据图像均值对灰度图像进行二值化/分割

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()
上一篇下一篇

猜你喜欢

热点阅读