Detect if the TIFF image is Horizontal or Vertical - C# - c#

Im using WinForms. In my Form i have a picturebox and a next button. I use this picturebox to display tiff images and i use the next button to navigate to the next page. The tiff documents are multipage images. The document I'm trying to view has a horizontal images and a vertical images like the example below. If its horizontal i want to size it (1100, 800), but if its vertical i want to size it (800, 1100). How do i do this? currently this is what i have but its not a good solution.
System.Drawing.Image img = System.Drawing.Image.FromFile(path_lbl.Text);
if (img.Height > img.Width)
{
pictureBox1.Width = 800;
pictureBox1.Height = 1300;
}
else
{
pictureBox1.Width = 1300;
pictureBox1.Height = 800;
}
I currently use this approach but this doesn't work because if the first image is vertical the if-statement will always execute the first condition pictureBox1.size(1300 , 800); With this method, if the next image is horizontal the condition will not ever re-size it horizontally.
Example Tiff image
http://www.filedropper.com/verticalandhorizontal
Quick Test Code
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace Demo
{
class TestForm : Form
{
public TestForm()
{
var panel = new Panel { Dock = DockStyle.Top, BorderStyle = BorderStyle.FixedSingle };
openButton = new Button { Text = "Open", Top = 8, Left = 16 };
prevButton = new Button { Text = "Prev", Top = 8, Left = 16 + openButton.Right };
nextButton = new Button { Text = "Next", Top = 8, Left = 16 + prevButton.Right };
path_lbl = new Label { Text = "", Top = 12, Left = 16 + nextButton.Right };
panel.Height = 16 + openButton.Height;
panel.Controls.AddRange(new Control[] { openButton, prevButton, nextButton, path_lbl });
pageViewer = new PictureBox { Dock = DockStyle.Fill, SizeMode = PictureBoxSizeMode.Zoom };
ClientSize = new Size(850, 1100 + panel.Height);
Controls.AddRange(new Control[] { panel, pageViewer });
openButton.Click += OnOpenButtonClick;
prevButton.Click += OnPrevButtonClick;
nextButton.Click += OnNextButtonClick;
Disposed += OnFormDisposed;
UpdatePageInfo();
}
private Button openButton;
private Button prevButton;
private Button nextButton;
private PictureBox pageViewer;
private PageBuffer pageData;
private int currentPage;
private Size pageSize;
public string path;
private Label path_lbl;
private void OnOpenButtonClick(object sender, EventArgs e)
{
using (var dialog = new OpenFileDialog())
{
if (dialog.ShowDialog(this) == DialogResult.OK)
Open(dialog.FileName);
path = dialog.FileName;
}
}
private void OnPrevButtonClick(object sender, EventArgs e)
{
SelectPage(currentPage - 1);
}
private void OnNextButtonClick(object sender, EventArgs e)
{
//var data = PageBuffer.Open(path,Size= new Size(850,1150));
SelectPage(currentPage + 1);
//Debug.WriteLine("Current Size: 1300, 800");
}
private void OnFormDisposed(object sender, EventArgs e)
{
if (pageData != null)
pageData.Dispose();
}
private void Open(string path)
{
var data = PageBuffer.Open(path, new Size(1500, 1500));
pageViewer.Image = null;
if (pageData != null)
pageData.Dispose();
pageData = data;
SelectPage(0);
}
private void SelectPage(int index)
{
pageViewer.Image = pageData.GetPage(index);
currentPage = index;
UpdatePageInfo();
}
private void UpdatePageInfo()
{
prevButton.Enabled = pageData != null && currentPage > 0;
nextButton.Enabled = pageData != null && currentPage < pageData.PageCount - 1;
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm());
}
}
class PageBuffer : IDisposable
{
public const int DefaultCacheSize = 12; //This is how much images it will have in memory
public static PageBuffer Open(string path, Size maxSize, int cacheSize = DefaultCacheSize)
{
return new PageBuffer(File.OpenRead(path), maxSize, cacheSize);
}
private PageBuffer(Stream stream, Size maxSize, int cacheSize)
{
this.stream = stream;
source = Image.FromStream(stream);
pageCount = source.GetFrameCount(FrameDimension.Page);
if (pageCount < 2) return;
pageCache = new Image[Math.Min(pageCount, Math.Max(cacheSize, 5))];
pageSize = source.Size;
if (!maxSize.IsEmpty)
{
float scale = Math.Min((float)maxSize.Width / pageSize.Width, (float)maxSize.Height / pageSize.Height);
pageSize = new Size((int)(pageSize.Width * scale), (int)(pageSize.Height * scale));
}
var worker = new Thread(LoadPages) { IsBackground = true };
worker.Start();
}
private void LoadPages()
{
while (true)
{
lock (syncLock)
{
if (disposed) return;
int index = Array.FindIndex(pageCache, 0, pageCacheSize, p => p == null);
if (index < 0)
Monitor.Wait(syncLock);
else
pageCache[index] = LoadPage(pageCacheStart + index);
}
}
}
private Image LoadPage(int index)
{
source.SelectActiveFrame(FrameDimension.Page, index);
return new Bitmap(source, pageSize);
}
private Stream stream;
private Image source;
private int pageCount;
private Image[] pageCache;
private int pageCacheStart, pageCacheSize;
private object syncLock = new object();
private bool disposed;
private Size pageSize;
public Image Source { get { return source; } }
public int PageCount { get { return pageCount; } }
public Image GetPage(int index)
{
if (disposed) throw new ObjectDisposedException(GetType().Name);
if (PageCount < 2) return Source;
lock (syncLock)
{
AdjustPageCache(index);
int cacheIndex = index - pageCacheStart;
var image = pageCache[cacheIndex];
if (image == null)
image = pageCache[cacheIndex] = LoadPage(index);
return image;
}
}
private void AdjustPageCache(int pageIndex)
{
int start, end;
if ((start = pageIndex - pageCache.Length / 2) <= 0)
end = (start = 0) + pageCache.Length;
else if ((end = start + pageCache.Length) >= PageCount)
start = (end = PageCount) - pageCache.Length;
if (start < pageCacheStart)
{
int shift = pageCacheStart - start;
if (shift >= pageCacheSize)
ClearPageCache(0, pageCacheSize);
else
{
ClearPageCache(pageCacheSize - shift, pageCacheSize);
for (int j = pageCacheSize - 1, i = j - shift; i >= 0; j--, i--)
Exchange(ref pageCache[i], ref pageCache[j]);
}
}
else if (start > pageCacheStart)
{
int shift = start - pageCacheStart;
if (shift >= pageCacheSize)
ClearPageCache(0, pageCacheSize);
else
{
ClearPageCache(0, shift);
for (int j = 0, i = shift; i < pageCacheSize; j++, i++)
Exchange(ref pageCache[i], ref pageCache[j]);
}
}
if (pageCacheStart != start || pageCacheStart + pageCacheSize != end)
{
pageCacheStart = start;
pageCacheSize = end - start;
Monitor.Pulse(syncLock);
}
}
void ClearPageCache(int start, int end)
{
for (int i = start; i < end; i++)
Dispose(ref pageCache[i]);
}
static void Dispose<T>(ref T target) where T : class, IDisposable
{
var value = target;
if (value != null) value.Dispose();
target = null;
}
static void Exchange<T>(ref T a, ref T b) { var c = a; a = b; b = c; }
public void Dispose()
{
if (disposed) return;
lock (syncLock)
{
disposed = true;
if (pageCache != null)
{
ClearPageCache(0, pageCacheSize);
pageCache = null;
}
Dispose(ref source);
Dispose(ref stream);
if (pageCount > 2)
Monitor.Pulse(syncLock);
}
}
}
}

Related

Iterate through list and apply fade effect

I have a list of images(Helper.theaterImagesInfo) that i am reading through a foreach loop and continuing infinite loop using while until a form closed. images display well with the code below
Application.DoEvents();
await Task.Delay(img.durationInMilliseconds);//img.durationInMilliseconds
this.PictureBox1.Image = img.ImageHere;
Now i want to implement fade effect to those images displaying. Each image is displayed after 5 seconds.
Function to apply fade:
private int intCount = 0;
private List<Bitmap> lstFade = new List<Bitmap>();
private void ApplyFade(Bitmap imgTarget, Bitmap imgSource)
{
int intX = 0;
int intY = 0;
int intAmount = 10;
Rectangle rctDest = new Rectangle(intX, intY,
imgTarget.Width, imgTarget.Height);
using (var tmpBitMap = new Bitmap(imgSource))
using (var gTemp = Graphics.FromImage(tmpBitMap))
for (int i = 0; i <= intAmount; i++)
{
gTemp.DrawImage(imgSource, intX, intY);
ColorMatrix cmColors = new ColorMatrix();
cmColors.Matrix33 = System.Convert.ToSingle(i /
(double)intAmount);
ImageAttributes iaAttributes = new ImageAttributes();
iaAttributes.SetColorMatrix(cmColors);
gTemp.DrawImage(imgTarget, rctDest, intX, intY,
imgTarget.Width, imgTarget.Height, GraphicsUnit.Pixel,
iaAttributes);
lstFade.Add((Bitmap)tmpBitMap.Clone());
}
}
Timer:
private void timer1_Tick(object sender, EventArgs e)
{
intCount += 2;
if (intCount > 10)
{
timer1.Stop();
}
else
{
PictureBox1.Image = lstFade[intCount];
}
}
and here reading list and applying fade to images
public int x=1;
private async void TheaterForm_Shown(object sender, EventArgs e)
{
if (this.PictureBox1.Image == null) SetDefaultImage();
if (Helper.theaterImagesInfo != null && Helper.theaterImagesInfo.Count >
0)
{
while (x == 1)
{
foreach (var img in Helper.theaterImagesInfo.ToList())
{
if (img.IsAnimated)
{
try
{
Application.DoEvents();
var imgS = new Bitmap(this.PictureBox1.Image);
await Task.Delay(img.durationInMilliseconds);
var imgT = new Bitmap(img.ImageHere);
ApplyFade(imgT, imgS);
intCount = 0;
timer1.Interval = 200;
timer1.Start();
}
catch { }
}
else
{
try
{
Application.DoEvents();
await Task.Delay(img.durationInMilliseconds);
var imgS = new Bitmap(this.PictureBox1.Image);
var imgT = new Bitmap(img.ImageHere);
ApplyFade(imgT, imgS);
intCount = 0;
timer1.Interval = 200;
timer1.Start();
}
catch { }
}
if (this.x == 0)
{
break; // exit the for loop early
}
}
}
SetDefaultImage();
}
}
Problem
Fade is applied between starting two images and then keep on the same fading process with those two images. Seems like ApplyFade function doesn't apply again the imgSource and imgTarget once passed through the parameter

MaterialSkin Right to Left custom Control

I'm using MaterialSkin UI controls , how can I change the control properties to Right to left, because it's by default Left to Right.
I think this is the code should be edited :
private void UpdateTabRects()
{
_tabRects = new List<Rectangle>();
//If there isn't a base tab control, the rects shouldn't be calculated
//If there aren't tab pages in the base tab control, the list should just be empty which has been set already; exit the void
if (_baseTabControl == null || _baseTabControl.TabCount == 0) return;
//Calculate the bounds of each tab header specified in the base tab control
using (var b = new Bitmap(1, 1))
{
using (var g = Graphics.FromImage(b))
{
_tabRects.Add(new Rectangle(SkinManager.FormPadding, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[0].Text, SkinManager.Font_Size11).Width, Height));
for (int i = 1; i < _baseTabControl.TabPages.Count; i++)
{
_tabRects.Add(new Rectangle(_tabRects[i - 1].Right, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[i].Text , SkinManager.Font_Size11).Width , Height));
}
}
}
}
and this is the full code for the control :
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
using MaterialSkin.Animations;
namespace MaterialSkin.Controls
{
public class MaterialTabSelector : Control, IMaterialControl
{
[Browsable(false)]
public int Depth { get; set; }
[Browsable(false)]
public MaterialSkinManager SkinManager => MaterialSkinManager.Instance;
[Browsable(false)]
public MouseState MouseState { get; set; }
private MaterialTabControl _baseTabControl;
public MaterialTabControl BaseTabControl
{
get { return _baseTabControl; }
set
{
_baseTabControl = value;
if (_baseTabControl == null) return;
_previousSelectedTabIndex = _baseTabControl.SelectedIndex;
_baseTabControl.Deselected += (sender, args) =>
{
_previousSelectedTabIndex = _baseTabControl.SelectedIndex;
};
_baseTabControl.SelectedIndexChanged += (sender, args) =>
{
_animationManager.SetProgress(0);
_animationManager.StartNewAnimation(AnimationDirection.In);
};
_baseTabControl.ControlAdded += delegate
{
Invalidate();
};
_baseTabControl.ControlRemoved += delegate
{
Invalidate();
};
}
}
private int _previousSelectedTabIndex;
private Point _animationSource;
private readonly AnimationManager _animationManager;
private List<Rectangle> _tabRects;
private const int TabHeaderPadding = 24;
private const int TabIndicatorHeight = 2;
public MaterialTabSelector()
{
SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer, true);
Height = 48;
_animationManager = new AnimationManager
{
AnimationType = AnimationType.EaseOut,
Increment = 0.04
};
_animationManager.OnAnimationProgress += sender => Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.Clear(SkinManager.ColorScheme.PrimaryColor);
if (_baseTabControl == null) return;
if (!_animationManager.IsAnimating() || _tabRects == null || _tabRects.Count != _baseTabControl.TabCount)
UpdateTabRects();
var animationProgress = _animationManager.GetProgress();
//Click feedback
if (_animationManager.IsAnimating())
{
var rippleBrush = new SolidBrush(Color.FromArgb((int)(51 - (animationProgress * 50)), Color.White));
var rippleSize = (int)(animationProgress * _tabRects[_baseTabControl.SelectedIndex].Width * 1.75);
g.SetClip(_tabRects[_baseTabControl.SelectedIndex]);
g.FillEllipse(rippleBrush, new Rectangle(_animationSource.X - rippleSize / 2, _animationSource.Y - rippleSize / 2, rippleSize, rippleSize));
g.ResetClip();
rippleBrush.Dispose();
}
//Draw tab headers
foreach (TabPage tabPage in _baseTabControl.TabPages)
{
var currentTabIndex = _baseTabControl.TabPages.IndexOf(tabPage);
Brush textBrush = new SolidBrush(Color.FromArgb(CalculateTextAlpha(currentTabIndex, animationProgress), SkinManager.ColorScheme.TextColor));
g.DrawString(tabPage.Text.ToUpper(), SkinManager.Font_Size11, textBrush, _tabRects[currentTabIndex], new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
textBrush.Dispose();
}
//Animate tab indicator
var previousSelectedTabIndexIfHasOne = _previousSelectedTabIndex == -1 ? _baseTabControl.SelectedIndex : _previousSelectedTabIndex;
var previousActiveTabRect = _tabRects[previousSelectedTabIndexIfHasOne];
var activeTabPageRect = _tabRects[_baseTabControl.SelectedIndex];
var y = activeTabPageRect.Bottom - 2;
var x = previousActiveTabRect.X + (int)((activeTabPageRect.X - previousActiveTabRect.X) * animationProgress);
var width = previousActiveTabRect.Width + (int)((activeTabPageRect.Width - previousActiveTabRect.Width) * animationProgress);
g.FillRectangle(SkinManager.ColorScheme.AccentBrush, x, y, width, TabIndicatorHeight);
}
private int CalculateTextAlpha(int tabIndex, double animationProgress)
{
int primaryA = SkinManager.ActionBarText.A;
int secondaryA = SkinManager.ActionBarTextSecondary.A;
if (tabIndex == _baseTabControl.SelectedIndex && !_animationManager.IsAnimating())
{
return primaryA;
}
if (tabIndex != _previousSelectedTabIndex && tabIndex != _baseTabControl.SelectedIndex)
{
return secondaryA;
}
if (tabIndex == _previousSelectedTabIndex)
{
return primaryA - (int)((primaryA - secondaryA) * animationProgress);
}
return secondaryA + (int)((primaryA - secondaryA) * animationProgress);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (_tabRects == null) UpdateTabRects();
for (var i = 0; i < _tabRects.Count; i++)
{
if (_tabRects[i].Contains(e.Location))
{
_baseTabControl.SelectedIndex = i;
}
}
_animationSource = e.Location;
}
private void UpdateTabRects()
{
_tabRects = new List<Rectangle>();
//If there isn't a base tab control, the rects shouldn't be calculated
//If there aren't tab pages in the base tab control, the list should just be empty which has been set already; exit the void
if (_baseTabControl == null || _baseTabControl.TabCount == 0) return;
//Calculate the bounds of each tab header specified in the base tab control
using (var b = new Bitmap(1, 1))
{
using (var g = Graphics.FromImage(b))
{
_tabRects.Add(new Rectangle(SkinManager.FormPadding, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[0].Text, SkinManager.Font_Size11).Width, Height));
for (int i = 1; i < _baseTabControl.TabPages.Count; i++)
{
_tabRects.Add(new Rectangle(_tabRects[i - 1].Right, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[i].Text , SkinManager.Font_Size11).Width , Height));
}
}
}
}
}
}
If you're using windows forms you would go into the properties of the tab control and make:
RightToLeft = Yes
and
RightToLeftLayout = True.
This is also a duplicate question:
How to make Managed Tab Control (MTC) appear right to left

Resizing and positioning panels in another panel

I'm giving my panels inside another panel (this panel is in a usercontrol) a fixed location and a maximum size that changes with the size of the panel there in. Neither the resize or location works properly. The resize does happen but its to quickly. The location is fine if you only have 1 pinpanel for output and input. When you have more then 1 the locations are fixed but you need to resize the panel to resize to see the other panels. Could you point me in the right direction if you see the problem?
I have a panel drawPanel in this case that i use as a sort of background for the usercontrol. Inside this drawPanel i'm placing pinpanels. I want these pinpanels to resize with the usercontrol and give them a fixed location
private void OnClickPinPanel(object source, EventArgs e)
{
if (source is PinPanel p)
{
int index;
if ((index = Array.IndexOf(inputPins, p)) >= 0)
{
ClickedPinPanel?.Invoke(index, true);
}
else
{
ClickedPinPanel?.Invoke(Array.IndexOf(outputPins, p), false);
}
}
//else log here
}
private void CreatePinPanels(bool isInput)
{
int x = 0;
int y = -(int)(this.Width * 0.05)/2;
if (isInput)
{
for (int i = 0; i < inputPins.Length; i++)
{
y += (i + 1) * (this.Height / inputPins.Length + 1);
inputPins[i] = new PinPanel()
{
Location = new Point(x, y),
Size = new Size((int)(this.Width * 0.05), (int)(this.Width * 0.05)),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right,
};
inputPins[i].Click += OnClickPinPanel;
}
}
else
{
x += this.Width - (int)(this.Width * 0.1);
for (int i = 0; i < outputPins.Length; i++)
{
y += (i + 1) * (this.Height / inputPins.Length+1);
outputPins[i] = new PinPanel()
{
Size = new Size((int)(this.Width * 0.1), (int)(this.Width * 0.1)),
Location = new Point(x, y),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right
};
outputPins[i].Click += OnClickPinPanel;
}
}
}
The result i get now is that the pinpanels get a fixed location but when you have more then 1 pinpanel, the location is wrong its like if he thinks that the usercontrol is bigger then it is Reality. In order to see all the pins i have to resize and get this After resize
I want it to look like this
expectations
Try something like this out.
Here is my test rig:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
numericUpDown1.Value = someChip1.NumberInputPins;
numericUpDown2.Value = someChip1.NumberOutputPins;
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
someChip1.NumberInputPins = (int)numericUpDown1.Value;
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
someChip1.NumberOutputPins = (int)numericUpDown2.Value;
}
}
Sample chip with 5 inputs and 3 outputs:
Here is my PinPanel UserControl (just draws an ellipse/pin the size of the control):
public partial class PinPanel : UserControl
{
public PinPanel()
{
InitializeComponent();
}
private void PinPanel_Paint(object sender, PaintEventArgs e)
{
Rectangle rc = new Rectangle(new Point(0, 0), new Size(this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1));
e.Graphics.DrawEllipse(Pens.Black, rc);
}
private void PinPanel_SizeChanged(object sender, EventArgs e)
{
this.Refresh();
}
}
And finally, my SomeChip UserControl:
public partial class SomeChip : UserControl
{
public event PinPanelClick ClickedPinPanel;
public delegate void PinPanelClick(int index, bool input);
private PinPanel[] inputPins;
private PinPanel[] outputPins;
private int _NumberInputPins = 2;
public int NumberInputPins
{
get {
return _NumberInputPins;
}
set
{
if (value > 0 && value != _NumberInputPins)
{
_NumberInputPins = value;
CreatePinPanels();
this.Refresh();
}
}
}
private int _NumberOutputPins = 1;
public int NumberOutputPins
{
get
{
return _NumberOutputPins;
}
set
{
if (value > 0 && value != _NumberOutputPins)
{
_NumberOutputPins = value;
CreatePinPanels();
this.Refresh();
}
}
}
public SomeChip()
{
InitializeComponent();
}
private void SomeChip_Load(object sender, EventArgs e)
{
CreatePinPanels();
RepositionPins();
}
private void SomeChip_SizeChanged(object sender, EventArgs e)
{
this.Refresh();
}
private void SomeChip_Paint(object sender, PaintEventArgs e)
{
int PinHeight;
// draw the input pin runs
if (inputPins != null)
{
PinHeight = (int)((double)this.Height / (double)_NumberInputPins);
for (int i = 0; i < NumberInputPins; i++)
{
int Y = (i * PinHeight) + (PinHeight / 2);
e.Graphics.DrawLine(Pens.Black, 0, Y, this.Width / 4, Y);
}
}
// draw the output pin runs
if (outputPins != null)
{
PinHeight = (int)((double)this.Height / (double)_NumberOutputPins);
for (int i = 0; i < NumberOutputPins; i++)
{
int Y = (i * PinHeight) + (PinHeight / 2);
e.Graphics.DrawLine(Pens.Black, this.Width - this.Width / 4, Y, this.Width, Y);
}
}
//draw the chip itself (takes up 50% of the width of the UserControl)
Rectangle rc = new Rectangle(new Point(this.Width / 4, 0), new Size(this.Width / 2, this.Height - 1));
using (SolidBrush sb = new SolidBrush(this.BackColor))
{
e.Graphics.FillRectangle(sb, rc);
}
e.Graphics.DrawRectangle(Pens.Black, rc);
RepositionPins();
}
private void CreatePinPanels()
{
if (inputPins != null)
{
for (int i = 0; i < inputPins.Length; i++)
{
if (inputPins[i] != null && !inputPins[i].IsDisposed)
{
inputPins[i].Dispose();
}
}
}
inputPins = new PinPanel[_NumberInputPins];
for (int i = 0; i < inputPins.Length; i++)
{
inputPins[i] = new PinPanel();
inputPins[i].Click += OnClickPinPanel;
this.Controls.Add(inputPins[i]);
}
if (outputPins != null)
{
for (int i = 0; i < outputPins.Length; i++)
{
if (outputPins[i] != null && !outputPins[i].IsDisposed)
{
outputPins[i].Dispose();
}
}
}
outputPins = new PinPanel[_NumberOutputPins];
for (int i = 0; i < outputPins.Length; i++)
{
outputPins[i] = new PinPanel();
outputPins[i].Click += OnClickPinPanel;
this.Controls.Add(outputPins[i]);
}
}
private void OnClickPinPanel(object sender, EventArgs e)
{
PinPanel p = (PinPanel)sender;
if (inputPins.Contains(p))
{
ClickedPinPanel?.Invoke(Array.IndexOf(inputPins, p), true);
}
else if (outputPins.Contains(p))
{
ClickedPinPanel?.Invoke(Array.IndexOf(inputPins, p), false);
}
}
private void RepositionPins()
{
int PinRowHeight, PinHeight;
if (inputPins != null)
{
PinRowHeight = (int)((double)this.Height / (double)_NumberInputPins);
PinHeight = (int)Math.Min((double)(PinRowHeight / 2), (double)this.Height * 0.05);
for (int i = 0; i < inputPins.Length; i++)
{
if (inputPins[i] != null && !inputPins[i].IsDisposed)
{
inputPins[i].SetBounds(0, (int)((i * PinRowHeight) + (PinRowHeight /2 ) - (PinHeight / 2)), PinHeight, PinHeight);
}
}
}
if (outputPins != null)
{
PinRowHeight = (int)((double)this.Height / (double)_NumberOutputPins);
PinHeight = (int)Math.Min((double)(PinRowHeight / 2), (double)this.Height * 0.05);
for (int i = 0; i < outputPins.Length; i++)
{
if (outputPins[i] != null && !outputPins[i].IsDisposed)
{
outputPins[i].SetBounds(this.Width - PinHeight, (int)((i * PinRowHeight) + (PinRowHeight / 2) - (PinHeight / 2)), PinHeight, PinHeight);
}
}
}
}
}

Getting values from mouse hover on a class object C#

I've a txt file with a 360 numbers, I must read all of these and draw a kind of Disc made of FillPie eachone colored in scale of grey due to the value of the list. Until here everything is quite simple.I made a class with the data(value in the txt and degree) of one single fillpie with a Paint method that draw it of the correct color.
this is the code of the class:
class DatoDisco
{
int valoreSpicchio;
int gradi;
public DatoDisco(int valoreTastatore, int gradiLettura)
{
valoreSpicchio = valoreTastatore;
gradi = gradiLettura;
}
public void Clear()
{
valoreSpicchio = 0;
gradi = 0;
}
private int ScalaGrigi()
{
int grigio = 0;
if (valoreSpicchio <= 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio < 0)
grigio = 0;
}
if (valoreSpicchio > 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio > 230)
grigio = 230;
}
return grigio;
}
public void Paint (Graphics grafica)
{
try
{
Brush penna = new SolidBrush(Color.FromArgb(255, ScalaGrigi(), ScalaGrigi(), ScalaGrigi()));
grafica.FillPie(penna, 0, 0, 400, 400, gradi, 1.0f);
}
catch
{
}
}
public int ValoreSpicchio
{
get
{
return valoreSpicchio;
}
}
public int Gradi
{
get
{
return gradi;
}
}
}
here is where I draw everything:
public partial class Samac : Form
{
libnodave.daveOSserialType fds;
libnodave.daveInterface di;
libnodave.daveConnection dc;
int rack = 0;
int slot = 2;
int scalaGrigi = 0;
int angolatura = 0;
List<int> valoriY = new List<int>();
//Disco disco = new Disco();
List<DatoDisco> disco = new List<DatoDisco>();
float[] valoriTastatore = new float[360];
public Samac()
{
InitializeComponent();
StreamReader dataStream = new StreamReader("save.txt");
textBox1.Text = dataStream.ReadLine();
dataStream.Dispose();
for (int i = 0; i <= 360; i++ )
chart1.Series["Series2"].Points.Add(0);
//AggiornaGrafico(textBox1.Text, chart1);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
string indirizzoIpPlc
{
get
{
FileIniDataParser parser = new FileIniDataParser();
IniData settings = parser.LoadFile("config.ini");
return settings["PLC_CONNECTION"]["PLC_IP"];
}
}
private void AggiornaGrafico(string nomeFile, Chart grafico, bool online)
{
int max = 0;
int min = 0;
grafico.Series["Series1"].Points.Clear();
grafico.Series["Series2"].Points.Clear();
grafico.Series["Series3"].Points.Clear();
grafico.Series["Series4"].Points.Clear();
grafico.ChartAreas[0].AxisX.Maximum = 360;
grafico.ChartAreas[0].AxisX.Minimum = 0;
grafico.ChartAreas[0].AxisY.Maximum = 500;
grafico.ChartAreas[0].AxisY.Minimum = -500;
String file = nomeFile;
valoriY.Clear();
disco.Clear();
if (online == false)
{
System.IO.File.WriteAllText("save.txt", nomeFile);
}
StreamReader dataStreamGrafico = new StreamReader(file);
StreamReader dataStreamScheda = new StreamReader("Scheda.sch");
string datasample;
string[] scheda = new string[56];
for (int i = 0; i < 56; i++)
{
scheda[i] = dataStreamScheda.ReadLine();
}
dataStreamScheda.Close();
int gradi = 1;
while ((datasample = dataStreamGrafico.ReadLine()) != null)
{
grafico.Series["Series2"].Points.Add(0);
grafico.Series["Series2"].Color = Color.Red;
grafico.Series["Series2"].BorderWidth = 3;
grafico.Series["Series3"].Points.Add(Convert.ToInt32(float.Parse(scheda[5])));
grafico.Series["Series3"].Color = Color.Green;
grafico.Series["Series3"].BorderWidth = 3;
grafico.Series["Series4"].Points.Add(Convert.ToInt32(-float.Parse(scheda[5])));
grafico.Series["Series4"].Color = Color.Green;
grafico.Series["Series4"].BorderWidth = 3;
grafico.Series["Series1"].Points.Add(int.Parse(datasample));
grafico.Series["Series1"].BorderWidth = 5;
valoriY.Add(int.Parse(datasample));
//disco.Add(int.Parse(datasample));
disco.Add(new DatoDisco(int.Parse(datasample), gradi));
gradi++;
}
dataStreamGrafico.Close();
max = Convert.ToInt32(chart1.Series["Series1"].Points.FindMaxByValue().YValues[0]);
min = Convert.ToInt32(chart1.Series["Series1"].Points.FindMinByValue().YValues[0]);
lblCampanatura.Text = (((float)max + min) / 2000.0).ToString();
lblSbandieramento.Text = (((float)max - min) / 1000.0).ToString();
if ((Math.Abs(max) > 800) || (Math.Abs(min) > 800))
{
if (Math.Abs(max) >= Math.Abs(min))
{
chart1.ChartAreas[0].AxisY.Maximum = max + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(max + 200);
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = min + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(min + 200);
}
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = 800;
chart1.ChartAreas[0].AxisY.Minimum = -800;
}
boxGraficaDisco.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
if (result == DialogResult.OK)
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
ToolTip tooltip = new ToolTip();
private int lastX;
private int lastY;
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
tooltip.Show("X:" + cursorX.ToString("0.00") + "Y:" + Convert.ToInt32(chart1.Series[0].Points[cursorX].YValues[0]).ToString(), this.chart1, e.Location.X + 20, e.Location.Y + 20);
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void button1_Click_1(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5]))+1;
if (File.Exists(textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"))
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Il File non esiste");
}
}
private void btnGrafMeno_Click(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5])) - 1;
if (indice >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Prima lettura disco");
}
}
private void btnConnetti_Click(object sender, EventArgs e)
{
fds.rfd = libnodave.openSocket(102, indirizzoIpPlc);
fds.wfd = fds.rfd;
if (fds.rfd > 0)
{
di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
di.setTimeout(1000000);
dc = new libnodave.daveConnection(di, 0, rack, slot);
int res = dc.connectPLC();
timer1.Start();
// AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
MessageBox.Show("Impossibile connettersi");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
int res;
res = dc.readBytes(libnodave.daveDB, 21, 40, 1, null);
if (res == 0)
{
var letturaDati = (dc.getS8At(0) & (1 << 0)) != 0;
if (letturaDati == true)
{
int puntatore = 30;
StreamWriter datiDisco = new StreamWriter("DatiDaPlc.csv");
datiDisco.WriteLine("X;" + "C;" + "Z;");
while (puntatore <= 10838)
{
res = dc.readBytes(libnodave.daveDB, 3, puntatore, 192, null);
if (res == 0)
{
for (int i = 0; dc.getU32At(i) != 0; i = i + 12)
{
datiDisco.Write(dc.getU32At(i).ToString() + ";");
datiDisco.Write(dc.getU32At(i + 4).ToString() + ";");
datiDisco.WriteLine(dc.getFloatAt(i + 8).ToString() + ";");
}
}
puntatore = puntatore + 192;
}
datiDisco.Close();
StreamReader lettura = new StreamReader("DatiDaPlc.csv");
StreamWriter scritt = new StreamWriter("Disco.csv");
var titolo = lettura.ReadLine();
var posizioneLettura = lettura.ReadLine();
var posX = posizioneLettura.Split(';');
int minX = Convert.ToInt32(posX[0]) - 5;
int maxX = Convert.ToInt32(posX[0]) + 5;
int contatore = 0;
while (!lettura.EndOfStream)
{
var line = lettura.ReadLine();
var values = line.Split(';');
if ((Convert.ToInt32(values[1]) >= contatore && Convert.ToInt32(values[1]) < contatore + 1000) && (Convert.ToInt32(values[0]) > minX && Convert.ToInt32(values[0]) <= maxX))
{
scritt.WriteLine(Convert.ToInt32(float.Parse(values[2]) * 1000).ToString());
contatore += 1000;
}
}
lettura.Close();
scritt.Close();
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
}
else
{
timer1.Stop();
MessageBox.Show("Disconnesso");
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
}
}
}
private void btnDisconnetti_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
timer1.Stop();
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void Samac_FormClosing(object sender, FormClosingEventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
libnodave.closeSocket(102);
timer1.Stop();
}
}
private void button1_Click_2(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void chart2_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart2.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
int cursorY = Convert.ToInt32(chart2.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y));
//tooltip.Show("X:" + chart2.Series[0].Points[cursorX].XValue.ToString() + "Y:" + chart2.Series[0].Points[cursorX].YValues[0].ToString(), this.chart2, e.Location.X + 20, e.Location.Y + 20);
tooltip.Show("X:" + cursorX.ToString() + "Y:#VALY" , this.chart2, e.Location.X + 20, e.Location.Y + 20);
//chart2.Series[0].ToolTip="#VALY";
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void boxGraficaDisco_Paint(object sender, PaintEventArgs e)
{
Graphics grafica = e.Graphics;
//disco.Paint(grafica);
foreach (DatoDisco d in disco)
{
d.Paint(grafica);
}
}
private void boxGraficaDisco_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
foreach (DatoDisco d in disco)
{
}
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
}
Now I need that when i go with the mouse over the drawn disc, a tooltip show me the data of the fillPie(degree and value of txt) but i can't figure out how.
Anyone can help me?
this is an image of the disc
Eventually it looks as if all you want is a function to get the angle between the mouse position and the center of the disc..
Here is a function to calculate an angle given two points:
double AngleFromPoints(Point pt1, Point pt2)
{
Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y);
double alpha = 0d;
if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d;
else
{
double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y));
alpha = Math.Acos(f) * 180d / Math.PI;
if (P.Y > 0) alpha = 360d - alpha;
}
return alpha;
}

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in InAirSignature.exe

I am doing a program with Emgu.CV in C#
and i receive this error when compiling
An unhandled exception of type 'System.IO.FileNotFoundException'
occurred in InAirSignature.exe
Additional information: Could not load file or assembly 'Emgu.CV.UI,
Version=2.9.0.1922, Culture=neutral, PublicKeyToken=7281126722ab4438'
or one of its dependencies. The system cannot find the file specified.
any ideas how to solve?
for my coding, a webcam is needed.
below is my coding.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.GPU;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using System.Diagnostics;
using System.Windows.Forms.DataVisualization.Charting;
using Emgu.CV.ML.Structure;
using Emgu.CV.ML;
using System.IO;
namespace InAirSignature
{
public partial class Main : Form
{
private Capture capture;
private Rectangle roi;
private Bgr redOrGreen;
private const int NUMBERS_OF_FRAMES = 90,
NUMBERS_OF_SIGN = 6,
NUMBERS_OF_FEATURES = 3, // X Y Averange
FEATURE_X = 0,
FEATURE_Y = 1,
TEST = NUMBERS_OF_SIGN - 1,
NUMBERS_OF_NEURONS = 15;
private const int frameHeight = 640;
private const int frameWidth = 480;
private List<Image<Gray, Byte>> imgGrayBuffer = new List<Image<Gray, Byte>>();
private List<int> pointX = new List<int>();
private List<int> pointY = new List<int>();
private int[][][] pointsOfSign, distanceBetweenPoints;
private double[] finalAverage;
private int[][] pointsOfSignReference;
private int[] distanceBetweenPointsForRefenceAndTest;
private int[] classes = {0,0,0,0,1,1,1,1,1,1};
private int resultMode = 0;
private int recordSign = 0;
private bool record = false;
private int counter = 0;
private Stopwatch stopWatch;
private const string SYSTEM_MESSAGE = "System Message: ",
WELCOME_MESSAGE = "Welcome! ";
Matrix<int> layerSize;
MCvANN_MLP_TrainParams parameters;
ANN_MLP network;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Form /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Form
public Main()
{
InitializeComponent();
#region Initialize graph
chartX.Series.Add("X1");
chartX.Series.Add("X2");
chartX.Series.Add("X3");
chartX.Series.Add("X4");
chartX.Series.Add("X5");
chartX.Series.Add("Xtest");
chartX.Series.Add("Xref");
chartY.Series.Add("Y1");
chartY.Series.Add("Y2");
chartY.Series.Add("Y3");
chartY.Series.Add("Y4");
chartY.Series.Add("Y5");
chartY.Series.Add("Ytest");
chartY.Series.Add("Yref");
chartX.Series["X1"].Color = Color.Blue;
chartX.Series["X2"].Color = Color.Green;
chartX.Series["X3"].Color = Color.Red;
chartX.Series["X4"].Color = Color.Pink;
chartX.Series["X5"].Color = Color.Purple;
chartX.Series["Xtest"].Color = Color.Aqua;
chartX.Series["Xref"].Color = Color.BlueViolet;
chartY.Series["Y1"].Color = Color.Blue;
chartY.Series["Y2"].Color = Color.Green;
chartY.Series["Y3"].Color = Color.Red;
chartY.Series["Y4"].Color = Color.Pink;
chartY.Series["Y5"].Color = Color.Purple;
chartY.Series["Ytest"].Color = Color.Aqua;
chartY.Series["Yref"].Color = Color.BlueViolet;
chartX.Series["X1"].ChartType = SeriesChartType.FastLine;
chartX.Series["X2"].ChartType = SeriesChartType.FastLine;
chartX.Series["X3"].ChartType = SeriesChartType.FastLine;
chartX.Series["X4"].ChartType = SeriesChartType.FastLine;
chartX.Series["X5"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xtest"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xref"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y1"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y2"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y3"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y4"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y5"].ChartType = SeriesChartType.FastLine;
chartY.Series["Ytest"].ChartType = SeriesChartType.FastLine;
chartY.Series["Yref"].ChartType = SeriesChartType.FastLine;
#endregion
#region Initialize Neural Network
layerSize = new Matrix<int>(new int[] { NUMBERS_OF_FEATURES, NUMBERS_OF_NEURONS, 1 });
parameters = new MCvANN_MLP_TrainParams();
parameters.term_crit = new MCvTermCriteria(10, 1.0e-8);
parameters.train_method = Emgu.CV.ML.MlEnum.ANN_MLP_TRAIN_METHOD.BACKPROP;
parameters.bp_dw_scale = 0.1;
parameters.bp_moment_scale = 0.1;
network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
#endregion
#region Initialize camera
capture = new Capture();
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, frameHeight);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, frameWidth);
#endregion
initializeData();
roi = new Rectangle(338, 2, 300, 300);
redOrGreen = new Bgr(Color.Red);
lblSM.Text = SYSTEM_MESSAGE + WELCOME_MESSAGE;
updateResult();
updateGraph();
Application.Idle += processFrame;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
capture.Stop();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Button
private void btnSign_Click(object sender, EventArgs e)
{
stopWatch = Stopwatch.StartNew();
record = true;
redOrGreen = new Bgr(Color.LightGreen);
if (sender == btnSign1)
recordSign = 1;
else if (sender == btnSign2)
recordSign = 2;
else if (sender == btnSign3)
recordSign = 3;
else if (sender == btnSign4)
recordSign = 4;
else if (sender == btnSign5)
recordSign = 5;
else
recordSign = 6;
}
private void btnPredict_Click(object sender, EventArgs e)
{
float predicted = predict(new int[,] { { distanceBetweenPointsForRefenceAndTest[0], distanceBetweenPointsForRefenceAndTest[1], distanceBetweenPointsForRefenceAndTest[2] } }, network);
string result;
if (predicted < Convert.ToDouble(lblThreshold.Text))
result = "Success";
else
result = "Fail";
lblSM.Text = SYSTEM_MESSAGE + "Matching result - " + result + ", value: " + predicted.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
saveSignReference();
network.Save(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Saved";
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "ID blank";
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
loadSignReference();
network.Load(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Loaded";
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
updateGraph();
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "Invalid ID";
}
}
private void btnTrainNN_Click(object sender, EventArgs e)
{
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
trainNN();
}
private void btnClear_Click(object sender, EventArgs e)
{
initializeData();
updateGraph();
updateResult();
calculateResult();
rbS1.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Check Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Check Box
private void cbBinaryImage_CheckedChanged(object sender, EventArgs e)
{
ibBinaryImage.Visible = !ibBinaryImage.Visible;
}
private void cbResult_CheckedChanged(object sender, EventArgs e)
{
pnlResult.Visible = !pnlResult.Visible;
}
private void cbSign_CheckedChanged(object sender, EventArgs e)
{
if (sender == cbSign1)
{
chartX.Series["X1"].Enabled = !chartX.Series["X1"].Enabled;
chartY.Series["Y1"].Enabled = !chartY.Series["Y1"].Enabled;
}
else if (sender == cbSign2)
{
chartX.Series["X2"].Enabled = !chartX.Series["X2"].Enabled;
chartY.Series["Y2"].Enabled = !chartY.Series["Y2"].Enabled;
}
else if (sender == cbSign3)
{
chartX.Series["X3"].Enabled = !chartX.Series["X3"].Enabled;
chartY.Series["Y3"].Enabled = !chartY.Series["Y3"].Enabled;
}
else if (sender == cbSign4)
{
chartX.Series["X4"].Enabled = !chartX.Series["X4"].Enabled;
chartY.Series["Y4"].Enabled = !chartY.Series["Y4"].Enabled;
}
else if (sender == cbSign5)
{
chartX.Series["X5"].Enabled = !chartX.Series["X5"].Enabled;
chartY.Series["Y5"].Enabled = !chartY.Series["Y5"].Enabled;
}
else if (sender == cbSignRefer)
{
chartX.Series["Xref"].Enabled = !chartX.Series["Xref"].Enabled;
chartY.Series["Yref"].Enabled = !chartY.Series["Yref"].Enabled;
}
else
{
chartX.Series["Xtest"].Enabled = !chartX.Series["Xtest"].Enabled;
chartY.Series["Ytest"].Enabled = !chartY.Series["Ytest"].Enabled;
}
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Radio Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Radio Button
private void rbS_CheckedChanged(object sender, EventArgs e)
{
if (sender == rbS1)
resultMode = 0;
else if (sender == rbS2)
resultMode = 1;
else if (sender == rbS3)
resultMode = 2;
else if (sender == rbS4)
resultMode = 3;
else
resultMode = 4;
updateResult();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Text Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Text Box
private void tbId_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btnLoad.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Function /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private void processFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> frame = capture.QueryFrame().Flip(FLIP.HORIZONTAL);
Image<Bgr, Byte> frameCrop = frame.Copy(new Rectangle(338, 2, 300, 300)); // copy a crop
Image<Gray, Byte> frameBinary;
if (counter == (NUMBERS_OF_FRAMES - 2))
redOrGreen = new Bgr(Color.Red);
frame.Draw(roi, redOrGreen, 2);
frameBinary = ImageProcessing.getSkin(frameCrop);
if (record == true)
{
imgGrayBuffer.Add(frameBinary);
counter++;
if (counter == NUMBERS_OF_FRAMES)
{
while (imgGrayBuffer.Count() > 0)
{
Point point = ImageProcessing.getHighestPoint(imgGrayBuffer.ElementAt(0));
imgGrayBuffer.RemoveAt(0);
pointX.Add(point.X);
pointY.Add(point.Y);
}
pointsOfSign[recordSign - 1][FEATURE_X] = pointX.ToArray();
pointsOfSign[recordSign - 1][FEATURE_X] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_X] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_Y] = pointY.ToArray();
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointX.Clear();
pointY.Clear();
calculateResult();
updateResult();
updateGraph();
record = false;
stopWatch.Stop();
lblSM.Text = SYSTEM_MESSAGE + "Time taken => " + stopWatch.Elapsed.TotalSeconds.ToString() + " seconds.";
if (cbAuto.Checked == true && recordSign == 6)
btnVerify.PerformClick();
recordSign = 0;
counter = 0;
}
}
ibMain.Image = frame;
if(cbBinaryImage.Checked == true)
ibBinaryImage.Image = frameBinary;
}
private int[] normalizePosition(int[] position)
{
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int midPoint = (min + max) / 2;
for (int i = 0; i < position.Count(); i++)
position[i] -= midPoint;
return position;
}
private int[] normalizeSize(int[] position)
{
const int targetSize = 300;
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int height = max - min;
if (height != 0)
height = targetSize / height;
for (int i = 0; i < position.Count(); i++)
position[i] *= height;
return position;
}
private void updateGraph()
{
foreach (var series in chartX.Series)
series.Points.Clear();
foreach (var series in chartY.Series)
series.Points.Clear();
for (int i = 0; i < NUMBERS_OF_FRAMES; i++)
{
chartX.Series["X1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_X][i]);
chartX.Series["X2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_X][i]);
chartX.Series["X3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_X][i]);
chartX.Series["X4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_X][i]);
chartX.Series["X5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_X][i]);
chartX.Series["Xref"].Points.AddXY
(i, pointsOfSignReference[0][i]);
chartX.Series["Xtest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_X][i]);
chartY.Series["Y1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_Y][i]);
chartY.Series["Y2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_Y][i]);
chartY.Series["Y3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_Y][i]);
chartY.Series["Y4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_Y][i]);
chartY.Series["Y5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_Y][i]);
chartY.Series["Yref"].Points.AddXY
(i, pointsOfSignReference[1][i]);
chartY.Series["Ytest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_Y][i]);
}
}
private void calculateResult()
{
int average = 0;
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
for (int j = 0; j < NUMBERS_OF_SIGN - 1; j++)
{
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPoints[i][j][k] = DTW.Distance(pointsOfSign[i][k], pointsOfSign[j][k]);
average += distanceBetweenPoints[i][j][k];
}
distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1] = average / 2;
average = 0;
}
for (int i = 0; i < NUMBERS_OF_SIGN -1; i++)
{
finalAverage[i] = 0.0;
for (int j = 0; j < NUMBERS_OF_SIGN; j++)
finalAverage[i] += distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1];
finalAverage[i] /= NUMBERS_OF_SIGN - 2;
}
average = 0;
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPointsForRefenceAndTest[k] = DTW.Distance(pointsOfSignReference[k], pointsOfSign[TEST][k]);
average += distanceBetweenPointsForRefenceAndTest[k];
}
distanceBetweenPointsForRefenceAndTest[NUMBERS_OF_FEATURES - 1] = average / 2;
}
private void updateResult()
{
tbResult1X.Text = distanceBetweenPoints[resultMode][0][0].ToString();
tbResult1Y.Text = distanceBetweenPoints[resultMode][0][1].ToString();
tbResult1A.Text = distanceBetweenPoints[resultMode][0][2].ToString();
tbResult2X.Text = distanceBetweenPoints[resultMode][1][0].ToString();
tbResult2Y.Text = distanceBetweenPoints[resultMode][1][1].ToString();
tbResult2A.Text = distanceBetweenPoints[resultMode][1][2].ToString();
tbResult3X.Text = distanceBetweenPoints[resultMode][2][0].ToString();
tbResult3Y.Text = distanceBetweenPoints[resultMode][2][1].ToString();
tbResult3A.Text = distanceBetweenPoints[resultMode][2][2].ToString();
tbResult4X.Text = distanceBetweenPoints[resultMode][3][0].ToString();
tbResult4Y.Text = distanceBetweenPoints[resultMode][3][1].ToString();
tbResult4A.Text = distanceBetweenPoints[resultMode][3][2].ToString();
tbResult5X.Text = distanceBetweenPoints[resultMode][4][0].ToString();
tbResult5Y.Text = distanceBetweenPoints[resultMode][4][1].ToString();
tbResult5A.Text = distanceBetweenPoints[resultMode][4][2].ToString();
tbTotalA.Text = finalAverage[resultMode].ToString();
tbRatX.Text = distanceBetweenPointsForRefenceAndTest[0].ToString();
tbRatY.Text = distanceBetweenPointsForRefenceAndTest[1].ToString();
tbRatA.Text = distanceBetweenPointsForRefenceAndTest[2].ToString();
}
private float predict(int[,] testingSetInt, ANN_MLP network)
{
Matrix<float> testingSet = new Matrix<float>(Utility.arrayIntToFloat(testingSetInt)),
prediction = new Matrix<float>(1, 1);
network.Predict(testingSet, prediction);
return prediction.Data[0, 0];
}
private ANN_MLP trainNN(int[] trainingClassesInt, int[,] trainingSetInt)
{
int numbers_of_training_set = 4,
numbers_of_data = trainingSetInt.GetUpperBound(0) + 1;
Matrix<float> trainingSet = new Matrix<float>(Utility.arrayIntToFloat(trainingSetInt)),
trainingClasses = new Matrix<float>(Utility.arrayIntToFloat(trainingClassesInt));
Matrix<float> trainingSetPositive = trainingSet.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainingSetNegative = trainingSet.GetRows(numbers_of_training_set, numbers_of_data, 1);
Matrix<float> trainClassesPositive = trainingClasses.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainClassesNegative = trainingClasses.GetRows(numbers_of_training_set, numbers_of_data, 1);
ANN_MLP network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
network.Train(trainingSet, trainingClasses, null, (Matrix<int>)null, parameters, Emgu.CV.ML.MlEnum.ANN_MLP_TRAINING_FLAG.DEFAULT);
return network;
}
private void trainNN()
{
// Getting the most closest signature
int index = 0;
for (int i = 1; i < NUMBERS_OF_SIGN - 1; i++)
if (finalAverage[index] > finalAverage[i])
index = i;
lblSM.Text = SYSTEM_MESSAGE + "Sign # no." + (index + 1).ToString() + " is the reference now!";
for (int i = 0; i < NUMBERS_OF_FEATURES - 1; i++)
pointsOfSignReference[i] = pointsOfSign[index][i];
int total_training_data = 10; // 4 positive, 6 negative
int total_features_for_training = 3; // dtw of x, dtw of y, width of sign
int[,] trainingSet = new int[total_training_data, total_features_for_training];
// Get the distance (x and y) between closest signature and the rest of signature into training set
// Feature 0 and 1 => dtw of x, dtw of y
for (int i = 0, current = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
if (i != index)
{
for (int j = 0; j < NUMBERS_OF_FEATURES; j++)
trainingSet[current, j] = distanceBetweenPoints[i][index][j];
current++;
}
}
// Generate negative data
int[] max_value = new int[NUMBERS_OF_FEATURES];
int[] min_value = new int[NUMBERS_OF_FEATURES];
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
for (int j = 0; j < NUMBERS_OF_FEATURES && i != index; j++)
{
if (max_value[j] < distanceBetweenPoints[i][index][j])
max_value[j] = distanceBetweenPoints[i][index][j];
if (min_value[j] > distanceBetweenPoints[i][index][j])
min_value[j] = distanceBetweenPoints[i][index][j];
}
}
Random random = new Random();
In your project, right click on the References, then look for the Emgu.CV.UI assembly and select it.

Categories