Bitmap/Histogram

Revision as of 18:36, 7 December 2008 by rosettacode>Dmitry-kazakov (Image histogram)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Extend the data storage type defined on this page to support image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing the histogram data format take care about the data type used for the counts. It must be at least NxM, where N is the image width and M is the image height.

Task
Bitmap/Histogram
You are encouraged to solve this task according to the task description, using any language you may know.

Histogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:

  • Convert image to grayscale;
  • Compute the histogram
  • Find the median of. The median is defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.
  • Replace each pixel of luminance lesser than the median to black, and others to white.

Use read/write ppm file, and grayscale image solutions.

Ada

Histogram of an image: <ada> type Pixel_Count is mod 2**64; type Histogram is array (Luminance) of Pixel_Count;

function Get_Histogram (Picture : Grayscale_Image) return Histogram is

  Result : Histogram := (others => 0);

begin

  for I in Picture'Range (1) loop
     for J in Picture'Range (2) loop
        declare
           Count : Pixel_Count renames Result (Picture (I, J));
        begin
           Count := Count + 1;
        end;
     end loop;
  end loop;
  return Result;

end Get_Histogram; </ada> Median of a histogram: <ada> function Median (H : Histogram) return Luminance is

  From  : Luminance   := Luminance'First;
  To    : Luminance   := Luminance'Last;
  Left  : Pixel_Count := H (From);
  Right : Pixel_Count := H (To);

begin

  while From /= To loop
     if Left < Right then
        From := From + 1;
        Left := Left + H (From);
     else
        To    := To    - 1;
        Right := Right + H (To);         
     end if;
  end loop;
  return From;

end Median; </ada> Conversion of an image to black and white art: <ada>

  F1, F2 : File_Type;

begin

  Open (F1, In_File, "city.ppm");
  declare
     X : Image := Get_PPM (F1);
     Y : Grayscale_Image := Grayscale (X);
     T : Luminance := Median (Get_Histogram (Y));
  begin
     Close (F1);
     Create (F2, Out_File, "city_art.ppm");
     for I in Y'Range (1) loop
        for J in Y'Range (2) loop
           if Y (I, J) < T then
              X (I, J) := Black;
           else
              X (I, J) := White;
           end if;
        end loop;
     end loop;      
     Put_PPM (F2, X);
  end;
  Close (F2);

</ada>