Построение гистограммы по данным вручную - C#

Узнай цену своей работы

Формулировка задачи:

Помогите не могу реализовать правильно построение гистограммы
using System;
using ImageProcessingLibrary;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
 
namespace ImageProcessingTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Clear();
 
            Stopwatch sw = new Stopwatch();
 
            Bitmap src = new Bitmap("example.jpg");
 
            IImageHandler handler = new Gistogramma();
 
            Console.WriteLine(handler.HandlerName);
 
            handler.Source = src;
 
            sw.Reset();
 
            sw.Start();
 
            handler.startHandle(new ProgressDelegate(showProgress));            
 
            sw.Stop();
 
            long time1 = sw.ElapsedMilliseconds;
 
            handler.Result.Save("out1.bmp", ImageFormat.Bmp);
 
            Console.WriteLine("\nPress any key");
 
            Console.ReadLine();
 
            Console.Clear();
 
            sw.Reset();
 
            sw.Start();
        
        }
 
        static void showProgress(double progress)
        {
 
            Console.SetCursorPosition(0, 1);
 
            Console.Write("{0,4:F}%", progress);
 
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
 
namespace ImageProcessingLibrary
{
 
    //Указатель на функцию обработки прогресса выполнения задачи
    public delegate void ProgressDelegate(double precent);
 
    public interface IImageHandler
    {        
        //получение осмысленного имени обработчика
        string HandlerName { get; }
 
        //Инициализация параметров обработчика
        void init(SortedList<string, object> parameters);
 
        //Установка изображения-источника
        Bitmap Source { set; }
 
        //Получение изображения-результата
        Bitmap Result { get; }
 
        //Запуск обработки
        void startHandle(ProgressDelegate progress);

    }
 
}
using System.Collections.Generic;
using System.Drawing;
 
namespace ImageProcessingLibrary
{
    public class Gistogramma : IImageHandler
    {
 
        private const string HANDLER_NAME = "Postroenie gistogramm";
 
        private Bitmap bitmap;

        public string HandlerName 
        {
            get { return HANDLER_NAME; }            
        }

        public void init(SortedList<string, object> parameters)
        {
            
        }

        public Bitmap Source 
        {
            set { bitmap = value; } 
        }

        public Bitmap Result 
        {
            get { return bitmap; }
        }
 
        //Запуск обработки
        public Image startHandle(Image image)
        {

              Bitmap barChart = null;
                if (image != null) 
                {
                    // определяем размеры гистограммы. В идеале, ширина должны быть кратна 768 - 
                    // по пикселю на каждый столбик каждого из каналов
                    int width = 768, height = 600;
                    // получаем битмап из изображения
                    Bitmap bmp = new Bitmap (image);
                    // создаем саму гистограмму
                    barChart = new Bitmap (width, height);
                    // создаем массивы, в котором будут содержаться количества повторений для каждого из значений каналов.
                    // индекс соответствует значению канала
                    int[] R = new int[256];
                    int[] G = new int[256];
                    int[] B = new int[256];
                    int i, j;
                    Color color;
                    // собираем статистику для изображения
                    for (i = 0; i < bmp.Width; ++i)
                        for (j = 0; j < bmp.Height; ++j) 
                        {
                            color = bmp.GetPixel (i, j);
                            ++R[color.R];
                            ++G[color.G];
                            ++B[color.B];
                        }
                    // находим самый высокий столбец, чтобы корректно масштабировать гистограмму по высоте
                    int max = 0;
                    for (i = 0; i < 256; ++i)
                    {
                        if (R[i] > max)
                            max = R[i];
                        if (G[i] > max)
                            max = G[i];
                        if (B[i] > max)
                            max = B[i];
                    }
                    // определяем коэффициент масштабирования по высоте
                    double point = (double)max / height;
                    // отрисовываем столбец за столбцом нашу гистограмму с учетом масштаба
                    for (i = 0; i < width - 3; ++i) 
                    {
                        for (j = height - 1; j > height - R[i / 3] / point; --j) 
                        {
                            barChart.SetPixel (i, j, Color.Red);
                        }
                        ++i;
                        for (j = height - 1; j > height - G[i / 3] / point; --j) 
                        {
                            barChart.SetPixel (i, j, Color.Green);
                        }
                        ++i;
                        for (j = height - 1; j > height - B[i / 3] / point; --j) 
                        {
                            barChart.SetPixel (i, j, Color.Blue);
                        }
                    }
                } else
                    barChart = new Bitmap (1, 1);
                return barChart;    
             }  
            }
 
        }

Решение задачи: «Построение гистограммы по данным вручную»

textual
Листинг программы
handler.startHandle(new ProgressDelegate(showProgress));

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

14   голосов , оценка 4.286 из 5
Похожие ответы