4
$\begingroup$

How to shade bins in an ImageHistogram to match the image GrayLevel?

Inputs

Import the following graphic:

gray level image

B = Import["https://i.sstatic.net/F3Fxc.png"];

Create a histogram of the pixel intensities:

ImageHistogram[B]

The output is

enter image description here

How to shade the histogram bins to match the image?

The goal is to shade the bins to match the image. For example, if the bin counts the number of pixels with GrayLevels between 0.09 and 0.1, the bin would be GrayLevel[0.09]

Attempts

ImageHistogram provides controls for Filling, yet I am unable to exploit FillingStyle.

While I can shade a graphics primitive using LinearGradientFilling[{Black, White}] (below), it was not clear how to apply this in ImageHistogram.

gradient shadind

Investigated, without luck, this post: Histograms of grayscale images and this post Difference of ImageHistogram and Histogram of grayscale image

$\endgroup$
3
  • $\begingroup$ I was trying ImageHistogram[B,6,ColorFunction->(GrayLevel[Floor[#,1/5]]&)], but it doesn't work -- the color is a gradient and not choppy as I desire! $\endgroup$
    – Adam
    Commented Oct 16, 2023 at 6:21
  • 2
    $\begingroup$ But ImageHistogram does support FillingStyle! Which version are you using? $\endgroup$
    – Domen
    Commented Oct 16, 2023 at 7:08
  • $\begingroup$ @Domen. You are correct. Thanks for catching that. (Using v 13.2) $\endgroup$
    – dantopa
    Commented Oct 17, 2023 at 2:33

2 Answers 2

5
$\begingroup$
B = RandomImage[1, {200, 200}];
ImageHistogram[B, ColorFunctionScaling -> False, ColorFunction -> GrayLevel]

enter image description here

With your image we have to scale the vertical axis to see anything. For example, with logarithmic scaling of the vertical axis:

B = Import["https://i.sstatic.net/F3Fxc.png"];
ImageHistogram[B, ColorFunctionScaling -> False, ColorFunction -> GrayLevel,
               ScalingFunctions -> "Log"]

enter image description here

$\endgroup$
4
$\begingroup$

Do it yourself using a bar chart:

B = Import["https://i.sstatic.net/F3Fxc.png"];
binned = ImageLevels[B, 256];
BarChart[binned[[All, 2]], ChartStyle -> (GrayLevel@*First /@ binned), PlotRange -> {0, 500}]

histogram of image gray levels

$\endgroup$
1
  • 1
    $\begingroup$ If you reduce the number of bins (currently 256) you'll be able to see that this doesn't produce a gradient but each bar has its own colour, as desired. $\endgroup$
    – flinty
    Commented Oct 16, 2023 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.