c++ opencv 16bit tiff图像学习笔记

发布时间 2023-09-04 11:36:34作者: 阿坦

1、读取图像基本信息:长、宽、通道数、灰度最大值、最小值、均值、方差值和灰度直方图

#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    //  读入图像
    Mat src = imread("C:\\Users\\MingYi-LZQ\\Desktop\\1.tif", IMREAD_UNCHANGED);
    if (src.empty())
    {
        printf("不能找到文件。\n");
        return -1;
    }
    namedWindow("input", WINDOW_NORMAL);
    imshow("input", src);

    int height = src.rows;
    int width = src.cols;
    int ch = src.channels();
    printf("宽:%d 高:%d 通道数:%d\n", width, height, ch);

    double min_val;
    double max_val;
    Point minloc;
    Point maxloc;
    minMaxLoc(src, &min_val, &max_val, &minloc, &maxloc);
    printf("最小值:%.2f 最大值:%.2f\n", min_val, max_val);

    //  均值方差
    Scalar s = mean(src);
    Mat mm, mstd;
    meanStdDev(src, mm, mstd);
    int rows = mstd.rows;
    printf("rows:%d\n", rows);
    if (rows == 1) {
        printf("均值: %.2f\n", s[0]);
        printf("方差: %.2f\n", mstd.at<double>(0, 0));
    }
    else if (rows == 3) {
        printf("均值: %.2f   %.2f   %.2f\n", s[0], s[1], s[2]);
        printf("方差: %.2f   %.2f   %.2f\n", mstd.at<double>(0, 0), mstd.at<double>(1, 0), mstd.at<double>(2, 0));
    }

    //  像素值统计信息,统计灰度直方图
    int bins = 256;
    vector<int> hist(bins);
    //  初始化灰度直方图
    for (int i = 0; i < bins; i++)
        hist[i] = 0;
    double bin_width = (max_val - min_val) / bins;
    printf("bins: %d    bin_width: %.3f\n", bins, bin_width);

    int index = 0;
    //统计灰度直方图
    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            int pv = src.at<ushort>(row, col);
            if (pv >= min_val && pv <= max_val) {
                index = (pv - min_val) / bin_width;
                if (index == bins)
                    index--;
                hist[index]++;
            }
        }
    }
    waitKey(0);
    destroyAllWindows();
    return 0;
}
View Code