[C#] Zliczanie pikseli
: 15 wrz 2013, o 22:53
Piszę program w C#. I mam taką zagwostkę. Jak zliczyć ilość pixeli na zaznaczonym obszarze ? od czego zacząć ?
Kod: Zaznacz cały
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace testowanie_powierzchni
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<PointF> m_Points = new List<PointF>();
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
m_Points.Add(new PointF(e.X, e.Y));
this.Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (m_Points.Count >= 2)
{
e.Graphics.DrawPolygon(Pens.Blue, m_Points.ToArray());
}
if (m_Points.Count > 0)
{
foreach (PointF pt in m_Points)
{
e.Graphics.FillRectangle(Brushes.Black, pt.X - punkt, pt.Y - punkt, punkt, punkt);
}
}
}
private void wczytywanieToolStripMenuItem_Click(object sender, EventArgs e)
{
var image = new System.Windows.Forms.OpenFileDialog();
image.Filter = "";
image.Title = "Select image";
if (image.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.IO.FileInfo File = new System.IO.FileInfo(image.FileName);
BackgroundImage = Image.FromFile(image.FileName);
}
}
}
Kod: Zaznacz cały
private static bool IsConvexPolygon()
{
if (!IsPolygon()) return false;
int rightTurns = 0;
int leftTurns = 0;
PointF start = m_Points[(m_Points.Count - 2)];
PointF end = m_Points[(m_Points.Count - 1)];
PointF next;
foreach(var p in m_Points)
{
next = p;
if (IsRightTurn(start, end, next))
rightTurns++;
else
leftTurns++;
start = end;
end = next;
}
return ((rightTurns > 0) && (leftTurns == 0))
|| ((leftTurns > 0) && (rightTurns == 0));
}
private static bool IsPolygon()
{
return m_Points.Count >= 3;
}
private static bool IsRightTurn(PointF start, PointF end, PointF next)
{
double a = GetVectorAngle(start, end);
double b = GetVectorAngle(end, next);
return CalculateAngleDifference(a, b) < 0;
}
private static double GetVectorAngle(PointF start, PointF end)
{
double output = 0;
if (end.Y - start.Y == 0)
{
if (end.X - start.X > 0)
output = 0;
else
output = Math.PI;
}
else
{
output = Math.Atan((end.X - start.X) / (end.Y - start.Y));
if (end.X - start.X < 0)
{
output += output > 0 ? -1 * Math.PI : Math.PI;
}
}
return output;
}
private static double CalculateAngleDifference(double first, double second)
{
double output = second - first;
if (output > Math.PI)
output -= 2 * Math.PI;
if (output < -1 * Math.PI)
output += 2 * Math.PI;
return output;
}IsConvexPolygon() to ona zwróci informację czy zawartość m_Points jest obszarem wypukłym. Zanim będzie to można policzyć metodą trójkątów trzeba jeszcze sprawdzić czy linie pomiędzy punktami z m_Points nie przecinają się.static z każdej metody w tym przykładzie powyżej.