Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
dissertatsia_2.docx
Скачиваний:
0
Добавлен:
01.07.2025
Размер:
695.84 Кб
Скачать

Приложение а Исходный код программы распознавания изображений

using System;

using System.IO;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Collections;

namespace Histogram

{

public partial class Form1 : Form

{

struct histogram

{

public int[] values;

public string filename;

}

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

OpenFileDialog ofd = new OpenFileDialog();

int[] source_histogram;

ofd.Title = "Выберите изображение";

ofd.Filter = "Изображения (*.jpg)|*.jpg| Изображения (*.bmp)|*.bmp ";

if (ofd.ShowDialog() == DialogResult.OK)

{

Image image = Image.FromFile(ofd.FileName);

pictureBox1.Image = image;

pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

source_histogram = GetHistogramm(image as Bitmap);

pictureBox2.Image = new Bitmap(pictureBox2.Size.Width, pictureBox2.Size.Height);

Graphics g;

g = Graphics.FromImage(pictureBox2.Image);

DrawHistogramm(g, new Size(pictureBox2.Width, pictureBox2.Height), source_histogram);

if (!File.Exists("base.dat")) {

MessageBox.Show("Сначало нужно добавить изображения в базу");

return;

}

ArrayList histograms;

histograms = LoadBase();

double[] metrics = new double[histograms.Count];

for (int i = 0; i < histograms.Count; i++) {

metrics[i] = calculate_metrics(((histogram)histograms[i]).values, source_histogram);

}

metrics.Min();

int min_metric_index = 0;

for (int i = 0; i < histograms.Count; i++)

{

if (metrics[i] < metrics[min_metric_index]) {

min_metric_index = i;

}

}

Image image2 = Image.FromFile(((histogram)histograms[min_metric_index]).filename);

pictureBox3.Image = image2;

pictureBox3.SizeMode = PictureBoxSizeMode.Zoom;

pictureBox4.Image = new Bitmap(pictureBox2.Size.Width, pictureBox2.Size.Height);

Graphics g2;

g2 = Graphics.FromImage(pictureBox4.Image);

DrawHistogramm(g2, new Size(pictureBox4.Width, pictureBox4.Height),

((histogram)histograms[min_metric_index]).values);

MessageBox.Show("Похожее изображение найдено. метрика = " + metrics[min_metric_index]);

};

}

private void button2_Click(object sender, EventArgs e) // обработчик события нажатия на кнопку "распознать изображение"

{

if (!Directory.Exists("images")) //проверяем существует ли директория для хранения изображений

{

Directory.CreateDirectory("images"); // создаем директория для хранения изображений

}

OpenFileDialog ofd = new OpenFileDialog();

ofd.Title = "Выберите изображение";

ofd.Filter = "Изображения (*.bmp)|*.bmp| Изображения (*.jpg)|*.jpg";

if (ofd.ShowDialog() == DialogResult.OK) // показываем диалог открытия файла

{

int[] histogram; //объявляем указатель на массив для хранения гистограммы

Image image = Image.FromFile(ofd.FileName); //открываем файл изображения

histogram = GetHistogramm(image as Bitmap); // вычисляем гистограмму изображения

StreamWriter fout = new StreamWriter("base.dat", true); //объявляем файловый дискриптор

for (int i = 0; i < histogram.Length; i++) //выводим в файл гистограмму

{

fout.Write(histogram[i].ToString());

if (i != histogram.Length-1)

fout.Write(';');

}

if (File.Exists("images//" + ofd.SafeFileName)) {

MessageBox.Show("Выбранное изображение уже содержится в базе");

}

File.Copy(ofd.FileName, "images//" + ofd.SafeFileName);

fout.Write('|' + "images//" + ofd.SafeFileName + '\n'); //выводим имя файла

fout.Close(); // закрываем файл

MessageBox.Show("Изображение добавлено в базу"); // показываем сообщение

}

}

private static void DrawHistogramm(Graphics g, Size rect, int[] hist)

{

float max = hist.Max();

if (max > 0)

for (int i = 0; i < hist.Length; i++)

{

float h = rect.Height * hist[i] / (float)max;

g.FillRectangle(Brushes.Green, i * rect.Width / (float)hist.Length, rect.Height - h, rect.Width / (float)hist.Length, h);

}

}

private static int[] GetHistogramm(Bitmap image)

{

int[] result = new int[256];

for (int x = 0; x < image.Width; x++)

for (int y = 0; y < image.Height; y++)

{

int i = (int)(255 * image.GetPixel(x, y).GetBrightness());

result[i]++;

}

return result;

}

public ArrayList LoadBase()

{

StreamReader fin = new StreamReader("base.dat");

string buf;

string[] tmp1;

ArrayList histograms = new ArrayList();

while (!fin.EndOfStream)

{

string[] tmp;

buf = fin.ReadLine();

tmp1 = buf.Split('|');

histogram h = new histogram();

h.filename = tmp1[1];

tmp = tmp1[0].Split(';');

h.values = new int[tmp.Length];

for (int i = 0; i < tmp.Length; i++)

{

h.values[i] = Convert.ToInt32(tmp[i]);

}

histograms.Add(h);

}

fin.Close();

return histograms;

}

public double calculate_metrics(int[] hist1, int[] hist2)

{

double tmp;

double result = 0;

for (int i = 0; i < hist1.Length; i++)

{

if (hist1[i] + hist2[i] != 0)

{

tmp = Math.Abs(hist1[i] - hist2[i]) / Math.Abs(hist1[i] + hist2[i]);

result += tmp;

}

}

return result;

}

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]