OpenCV 直方图和归一化
  WBP15ByhMECz 2023年11月30日 41 0

直方图可以反映图片的整体统计信息, 使用函数 CalcHist() 实现.
但CalcHist() 统计出的数量信息和图像大小相关, 如果要剔除图像大小因素, 需要做归一化处理, 归一化处理后的信息, 反映出各个颜色值得占比情况, 这样更方便不同size图像做对比, 归一化的函数为 Normalize().

/// <summary>
        /// computes the joint dense histogram for a set of images.
        /// </summary>
        /// <param name="images">要统计直方图的Mat</param>
        /// <param name="channels">需要统计的通道Id, 为了理解方便, 一般仅统计一个通道</param>
        /// <param name="mask">掩码Mat, 如果是整张图片统计直方图, 传null即可</param>
        /// <param name="hist">统计后的hist mat</param>
        /// <param name="dims">输出直方图的维度, 灰度为1, 彩色为3</param>
        /// <param name="histSize">直方图横坐标的区间数, 即直方图每一维数组的大小</param>
        /// <param name="ranges">执直方图每个bin上下浮动的数值范围</param>
        /// <param name="uniform">直方图是否均匀, 一般取值为true</param>
        /// <param name="accumulate">累计标志, 多次进行直方图统计时是否需要累计, 一般取值为false</param>
        public static void CalcHist(Mat[] images, 
            int[] channels, InputArray? mask,
            OutputArray hist, int dims, int[] histSize,
            Rangef[] ranges, bool uniform = true, bool accumulate = false)
        {}
/// <summary>
        /// scales and shifts array elements so that either the specified norm (alpha) 
        /// or the minimum (alpha) and maximum (beta) array values get the specified values
        /// </summary>
        /// <param name="src">直方图hist mat</param>
        /// <param name="dst">归一化后的Mat, 归一化前后的mat具有相同的size</param>
        /// <param name="alpha">如果beta参数为0, alpha值为归一化后的下限值;  如果beta值>0; alpha值为归一化后的上限值;</param>
        /// <param name="beta">如果beta>0, 即指定归一化后的上限值</param>
        /// <param name="normType">归一化的算法</param>
        /// <param name="dtype"> 如dtype<0, 归一化后的数据类型同归一化之前的数据类型, 一般取-1即可</param>
        /// <param name="mask">掩码区</param>
        public static void Normalize(InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,
            NormTypes normType = NormTypes.L2, int dtype = -1, InputArray? mask = null)

归一化有两类算法:

  • 范围归一化, 上下限为[alpha, beta] , 算法需要使用 norm_type= NormTypes.MinMax, 函数会进行比例变换, 将数值从[min(src),max(src)]变换到[alpha,beta]区间.
  • 范数归一化, 上下限为 [0, alpha],
    . 算法取值为NORM_INF,此时函数normalize()会把src矩阵所有元素的最大绝对值调整为参数alpha的值。
    . 算法取值为NORM_L1,此时函数normalize()会把src矩阵所有元素的绝对值之和调整为参数alpha的值。
    . 算法取值为NORM_L2,此时函数normalize()会把src矩阵所有元素的绝对值的平方和进行开方后的值调整为参数alpha的值。

示例代码

private void calcHistTest()
{
    string fileName = @"D:\my_workspace\opencv\images\lena2.jpg";
    var lena = Cv2.ImRead(fileName, ImreadModes.Color);
    //var lena = new Mat(500, 500, MatType.CV_8UC3, Scalar.Blue);

    //分离BGR通道
    Mat[] bgr = lena.Split();

    //分别对BGR mat进行直方图统计
    int binCount = 256;
    Mat blueHist = new Mat();
    Cv2.CalcHist(new Mat[] { bgr[0] }, channels: new int[] { 0 },
        mask: null, hist: blueHist, dims: 1, histSize: new int[] { binCount }, ranges: new Rangef[] { new Rangef(0, 256) });
    Mat greenHist = new Mat();
    Cv2.CalcHist(new Mat[] { bgr[1] }, channels: new int[] { 0 },
        mask: null, hist: greenHist, dims: 1, histSize: new int[] { binCount }, ranges: new Rangef[] { new Rangef(0, 256) });
    Mat redHist = new Mat();
    Cv2.CalcHist(new Mat[] { bgr[2] }, channels: new int[] { 0 },
        mask: null, hist: redHist, dims: 1, histSize: new int[] { binCount }, ranges: new Rangef[] { new Rangef(0, 256) });

    //分别做归一化, 归一化到 [0,1]
    Cv2.Normalize(blueHist, blueHist, 0, 1, NormTypes.MinMax);
    Cv2.Normalize(greenHist, greenHist, 0, 1, NormTypes.MinMax);
    Cv2.Normalize(redHist, redHist, 0, 1, NormTypes.MinMax);

    //绘制直方图
    int histWidth = 500;
    int histHeight = 500;
    int binWidth = histWidth / binCount;
    var histImage = new Mat(histWidth, histHeight, MatType.CV_8UC3, Scalar.Black);
    for (int i = 1; i < binCount; i++)
    {
        histImage.Line(new OpenCvSharp.Point((i - 1) * binWidth, blueHist.At<float>(i - 1) * histHeight),
            new OpenCvSharp.Point(i * binWidth, blueHist.At<float>(i) * histHeight), Scalar.Blue);
        histImage.Line(new OpenCvSharp.Point((i - 1) * binWidth, greenHist.At<float>(i - 1) * histHeight),
            new OpenCvSharp.Point(i * binWidth, greenHist.At<float>(i) * histHeight), Scalar.Green);
        histImage.Line(new OpenCvSharp.Point((i - 1) * binWidth, redHist.At<float>(i - 1) * histHeight),
            new OpenCvSharp.Point(i * binWidth, redHist.At<float>(i) * histHeight), Scalar.Red);
    }

    //比较两个归一化的直方图
    var anotherBlueHist = blueHist.Clone();
    var compareResult = Cv2.CompareHist(anotherBlueHist, blueHist, HistCompMethods.Correl);
    Console.WriteLine($"compareResult:{compareResult}");

    Cv2.ImShow("lena", lena);
    Cv2.ImShow("histImage", histImage);
    Cv2.WaitKey();
    Cv2.DestroyAllWindows();
}

参考:

https://zhuanlan.zhihu.com/p/258118645

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: OpenAI崩了 下一篇: PySimpleGUI+多线程
  1. 分享:
最后一次编辑于 2023年11月30日 0

暂无评论

WBP15ByhMECz