001/*******************************************************************************
002 * This software is provided as a supplement to the authors' textbooks on digital
003 * image processing published by Springer-Verlag in various languages and editions.
004 * Permission to use and distribute this software is granted under the BSD 2-Clause
005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause).
006 * Copyright (c) 2006-2023 Wilhelm Burger, Mark J. Burge. All rights reserved.
007 * Visit https://imagingbook.com for additional details.
008 ******************************************************************************/
009
010package imagingbook.common.histogram;
011
012import ij.ImagePlus;
013import ij.process.ByteProcessor;
014
015/**
016 * Defines a simple image window to display histograms. This is a sub-class of {@link ImagePlus} (similar to
017 * {@code ij.gui.HistogramPlot}).
018 *
019 * @author WB
020 * @version 2022/12/07
021 */
022public class HistogramPlot extends ImagePlus {
023        
024        private static final int Background = 255;
025        private static final int Foreground = 0;
026    private static final int width =  256;
027    private static final int height = 128;
028
029        /**
030         * Constructor for a normalized discrete distribution.
031         *
032         * @param nH a normalized discrete distribution with values in [0,1]
033         * @param title the window title to be displayed (may be null)
034         */
035        public HistogramPlot(double[] nH, String title) {
036                super(title, drawHistogram(nH));
037        }
038
039        /**
040         * Constructor for a discrete distribution.
041         *
042         * @param h a discrete distribution (histogram) with arbitrary values
043         * @param title the window title to be displayed (may be null)
044         */
045        public HistogramPlot(int[] h, String title) {
046                this(HistogramUtils.normalizeMax(h), title);
047        }
048
049        private static ByteProcessor drawHistogram(double[] nH) {
050                ByteProcessor ip = new ByteProcessor(width, height);
051                int base = height - 1;
052                ip.setValue(Background);
053                ip.fill();
054                ip.setValue(Foreground);
055                ip.drawLine(0, base, width - 1, base);
056                int u = 0;
057                for (int i = 0; i < nH.length; i++) {
058                        int k = (int) Math.round(height * nH[i]);
059                        if (k > 0) {
060                                ip.drawLine(u, base - 1, u, base - k);
061                        }
062                        u = u + 1;
063                }
064                return ip;
065        }
066        
067}