'Emgu.CV.Invoke' threw an exception - c#

I am relativity new EmguCV but I have done a lot of research and read a few tutorials and look through this site for the answer. All of the other people with similar problems are told to add the unmangaged dll to the output folder. I have done this and I am still getting this error 'Emgu.CV.Invoke' threw an exception.
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.VFW;
using System.Drawing.Imaging;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class SandBox : Form
{
private bool DeviceExist = false;
public VideoCaptureDevice FinalVideoSource;
public FilterInfoCollection VideoCaptureDevices;
private Capture capture;
private VideoWriter captureOutput;
private void FinalVideoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgseventArgs)
{
Bitmap image = (Bitmap)eventArgs.Frame.Clone();
image.RotateFlip(RotateFlipType.Rotate180FlipY);
pictureBox1.Image = image;
}
public SandBox()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = " ";
FPS.Text = " ";
try
{
VideoCaptureDevices = new FilterInfoCollection(AForge.Video.DirectShow.FilterCategory.VideoInputDevice);
DeviceExist = true;
foreach (AForge.Video.DirectShow.FilterInfo VideoCaptureDevice in VideoCaptureDevices)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No device on your system");
}
}
private void Start_Click(object sender, EventArgs e)
{
FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[comboBox1.SelectedIndex].MonikerString);
FinalVideoSource.NewFrame += new NewFrameEventHandler(FinalVideoSource_NewFrame);
FinalVideoSource.Start();
label1.Text = "Device running...";
Start.Enabled = false;
Stop.Enabled = true;
timer1.Enabled = true;
capture = new Capture();
captureOutput = new VideoWriter("test.avi", 30, 1280, 720, true);
Image<Bgr, Byte> ImageFrame = capture.QueryFrame();
captureOutput.WriteFrame(ImageFrame);
}
}
The error is being thrown in line capture = new Capture();. I cant figure out what is wrong with the project. Just to clarify I am only using EmguCV to record video not to display it on screen. Any help would be greatly appreciated.

The type initializer for 'Emgu.CV.CvInvoke' threw an exception its means that EMGU.CV file is not dectecting by code. this is due to system dependency. you need to go in to configration manger window in visual stdio and choose your required platform and then copy respective dll files(64 dll files forx64 and 32bit dll for x86 can be downloaded from emgu website ) according to your platform. copile it now there is no error like emgu.cv.invoke
http://www.emgu.com/wiki/index.php/Setting_up_EMGU_C_Sharp

Related

Can't control arduino analog read via Visual Studio GUI

I'm trying to make GUI for my arduino analogread. The GUI display graph and text line of the value that arduino read. I'm using zedgraph for graphing.
I need to write "on" in the serial monitor window of arduino to start the readings. it runs well. But when I try to control via GUI I made with C# Visual
Studio, the reading won't start. it says "Access to the port 'COM3' is denied".
Here's my arduino code:
void loop() {
while (Serial.available() > 0)
{
input += (char) Serial.read(); // Read in one char at a time
delay(5);
} if (input == "on")
{
myservo.write(0);
---analog reading and Serial.println arduino---
} if (input == "off")
{
myservo.write(115);
}
}
And this is my visual studio code:
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 ZedGraph;
using System.IO.Ports;
using System.Globalization;
namespace concentrationMeasurement
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = port_name.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
myport.WriteLine("on");
data_tb.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Error");
}
}
private void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
data_tb.AppendText(time + "\t\t" + in_data + "\n");
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void save_btn_Click(object sender, EventArgs e)
{
try{
string pathfile = #"C:\Users\ajis.aprl\Documents\TA bgt\data_GUI\";
string filename = "concentration.txt";
System.IO.File.WriteAllText(pathfile + filename, data_tb.Text);
MessageBox.Show("Data has been saved to "+pathfile,"Save File");
}
catch (Exception ex3){
MessageBox.Show(ex3.Message, "Error");
}
}
private void Form1_Load(object sender, EventArgs e)
{
plotGraph();
SetSize();
}
private void plotGraph()
{
GraphPane myPane = zedGraphControl1.GraphPane;
myPane.Title.Text = "Concentration Growth";
myPane.XAxis.Title.Text = "time";
myPane.YAxis.Title.Text = "concentration";
}
}
}
So I got 2 problem here:
As I said, I can't run my analog reading via GUI, it says "Access to the port 'COM3' is denied".
in myPane.Title.Text, myPane.XAxis.Title.Tex, and myPane.YAxis.Title.Text, there's error in "Text" it says:
"Error 3 'string' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)"
I googled everywhere but I can't find the answer. Please if anyone know what I'm missing. Can you tell me what's wrong with my code/logic? Thank you.

webcam Afroge unhandled exception: Afroge.Video.DirectShow

i am working to make a c# program that can start streaming webcam, close and capture the still image when closing.
the programs work as excepted on my development machine but when i open it on other it dosent work and gives me unhandled exception: Afroge.Video.DirectShow error.
I have added references AFroge.Video.dll and AFroge.Video.DirectShow.dll
here is the exe file and code of my project.
sendspace .com/file/4okqsi
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Create using directives for easier access of AForge library's methods
using AForge.Video;
using AForge.Video.DirectShow;
namespace aforgeWebcamTutorial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Create webcam object
VideoCaptureDevice videoSource;
private void Form1_Load(object sender, EventArgs e)
{
}
void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
//Cast the frame as Bitmap object and don't forget to use ".Clone()" otherwise
//you'll probably get access violation exceptions
pictureBoxVideo.BackgroundImage = (Bitmap)eventArgs.Frame.Clone();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
//Stop and free the webcam object if application is closing
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
try {
if (videoSource.IsRunning)
{
videoSource.Stop();
pictureBoxVideo.BackgroundImage.Save("abc.png");
pictureBoxVideo.BackgroundImage = null;
}
}
catch (Exception er) { }
}
private void button2_Click(object sender, EventArgs e)
{
try {
//List all available video sources. (That can be webcams as well as tv cards, etc)
FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//Check if atleast one video source is available
if (videosources != null)
{
//For example use first video device. You may check if this is your webcam.
videoSource = new VideoCaptureDevice(videosources[0].MonikerString);
try
{
//Check if the video device provides a list of supported resolutions
if (videoSource.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
{
if (videoSource.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
//Set the highest resolution as active
videoSource.VideoResolution = videoSource.VideoCapabilities[Convert.ToInt32(highestSolution.Split(';')[1])];
}
}
catch { }
//Create NewFrame event handler
//(This one triggers every time a new frame/image is captured
videoSource.NewFrame += new AForge.Video.NewFrameEventHandler(videoSource_NewFrame);
//Start recording
videoSource.Start();
}
}
catch (Exception er) { }
}
}
}
Try this link!
It worked for me!
If some parts cannot be installed. Delete all of the assemblies of AForge.Net and follow following tutorial.
https://premsivakumar.wordpress.com/2010/06/28/aforge-net-visual-studio-2010-setup-tutorial/

recording microphone audio using NAudio in a console application

my code runs and creates a test.wav but this file dosent contain aything. i am trying to run this code in a console application. please help
using System;
using System.Media;
using NAudio;
using NAudio.Wave;
class sound
{
public static void Main()
{
WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(0);
Console.WriteLine("Now recording...");
WaveInEvent waveSource = new WaveInEvent();
waveSource.DeviceNumber = 0;
waveSource.WaveFormat = new WaveFormat(16000, deviceInfo.Channels);
//waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
string tempFile = (#"C:\Users\user\Desktop\test1.wav");
WaveFileWriter waveFile = new WaveFileWriter(tempFile, waveSource.WaveFormat);
waveSource.StartRecording();
}
//void waveInStream_DataAvailable(object sender, WaveInEventArgs e)
//{
// wavefile.WriteData(e.Buffer, 0, e.BytesRecorded);
//}
}
and can someone please explain what do the lines which are commented mean. i am a beginner in programming.
when i compile the program it gives 2 errors:
Error 1: An object reference is required for the non-static field, method, or property 'sound.waveSource_DataAvailable(object, NAudio.Wave.WaveInEventArgs)' C:\Users\user\Documents\Visual Studio 2008\Projects\sound\sound\Program.cs 18 49 sound
Error 2 The name 'wavefile' does not exist in the current context C:\Users\user\Documents\Visual Studio 2008\Projects\sound\sound\Program.cs 28 21 sound
Apparently the StartRecording methods start some capture loops that periodically raises the DataAvailable event to allow the user collecting the recorded data. In your example code the event handle properly append the recorded data to the file tempFile. Both the function waveInStream_DataAvailable and the waveFile must be declared as static.
Try this:
using System;
using System.Media;
using NAudio;
using NAudio.Wave;
class sound
{
static WaveFileWriter waveFile;
public static void Main()
{
//WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(0);
Console.WriteLine("Now recording...");
WaveInEvent waveSource = new WaveInEvent();
//waveSource.DeviceNumber = 0;
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
string tempFile = (#"C:\Users\user\Desktop\test1.wav");
waveFile = new WaveFileWriter(tempFile, waveSource.WaveFormat);
waveSource.StartRecording();
Console.WriteLine("Press enter to stop");
Console.ReadLine();
waveSource.StopRecording();
waveFile.Dispose();
}
static void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
waveFile.WriteData(e.Buffer, 0, e.BytesRecorded);
}
}

Speech Recognition to display pictures from a listbox

I am having an error with this Speech Recognition, I keep getting "At least one grammar must be loaded before doing a recognition" I can't get the images to display when you say its corresponding linked name.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SpeechLib;
using System.IO;
using System.Speech.Recognition;
using System.Globalization;
namespace SimpleSpeechRecognition
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SpeechRecognitionEngine recognizer;
private void Form1_Load(object sender, EventArgs e)
{
speechListBox1.Items.Add("Dog");
speechListBox1.Items.Add("Elephant");
speechListBox1.SpeechEnabled = true;
recognizer = new SpeechRecognitionEngine(new CultureInfo("en-GB"));
recognizer.SetInputToDefaultAudioDevice();
Choices choices = new Choices("Dog", "Elephant");
GrammarBuilder m_GrammarBuilder = new GrammarBuilder(choices);
Grammar m_Speech = new Grammar(m_GrammarBuilder);
recognizer.LoadGrammar(m_Speech);
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
foreach (RecognizedWordUnit word in e.Result.Words)
{
switch (word.Text)
{
case "Dog":
pictureBox1.Image = Image.FromFile("C:\\" + "dog.jpg");;
break;
case "Elephant":
pictureBox1.Image = Image.FromFile("C:\\" + "elephant.jpg");
break;
}
}
}
private void speechListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//MessageBox.Show(speechListBox1.SelectedItems[0].ToString());
SayPhrase(speechListBox1.SelectedItems[0].ToString());
//pictureBox1.Image = Image.FromFile("C:\\" + "dog.jpg");
//pictureBox1.Image = Image.FromFile(((FileInfo)speechListBox1.SelectedItem).FullName);
pictureBox1.Refresh();
}
private void SayPhrase(string PhraseToSay )
{
SpeechVoiceSpeakFlags SpFlags = new SpeechVoiceSpeakFlags();
SpVoice Voice = new SpVoice();
Voice.Speak(PhraseToSay, SpFlags);
}
}
}
The errors self-explanatory:
The speech engine must have a collection of 'Choices' to listen out for, however these need to be built into appropriate Grammar for the speech engine to listen out for.
GrammarBuilder m_GrammarBuilder = new GrammarBuilder(choices);
Grammar m_Speech = (m_GrammarBuilder);
Then just load the grammar in:
recognizer.LoadGrammar(m_Speech);
I think that should solve your problem. It also worth noting that you can unload and load different sets of grammar via the .UnloadGrammar() function as well.
Additionally, it's also worth initializing a SpeechRecognitionEngine with an appropriate culture info. For English (UK) this is:
new SpeechRecognitionEngine(new CultureInfo("en-GB"))

UI Freezes while processing frames from Kinect using EmguCV in WPF C# Application

I am working on a project which involves extracting features from color and depth frames from Kinect Camera. The problem I am facing is that whenever I try displaying 2 Images, the UI hangs. When I tried debugging, the depthFrame and colorFrame were coming as null. If enable only the color steam then both colorImage and featureImage1 are displayed properly and if I enable only the depth stream, it works as it should. But when I enable them both, the UI hangs. I have no idea what is causing the problem. I have the following the following code for my Kinect Application. What is the cause of this problem and how can I fix it?
Config: Windows 8 Pro 64bit, 2Ghz Core2Duo, VisualStudio 2012 Ultimate, EmguCV 2.4.0.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
using Emgu.CV;
using Emgu.CV.WPF;
using Emgu.CV.Structure;
using Emgu.Util;
namespace features
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private Image<Bgra, Byte> cvColorImage;
private Image<Gray, Int16> cvDepthImage;
private int colorWidth = 640;
private int colorHeight = 480;
private int depthWidth = 640;
private int depthHeight = 480;
private static readonly int Bgr32BytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel + 7) / 8;
private byte[] colorPixels;
private byte[] depthPixels;
private short[] rawDepthData;
private bool first = true;
private bool firstDepth = true;
Image<Bgra, byte> image2;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
kinectSensorChooser.KinectSensorChanged += new DependencyPropertyChangedEventHandler(kinectSensorChooser_KinectSensorChanged);
}
void kinectSensorChooser_KinectSensorChanged(object sender, DependencyPropertyChangedEventArgs e)
{
KinectSensor oldSensor = (KinectSensor)e.OldValue;
KinectStop(oldSensor);
KinectSensor _sensor = (KinectSensor)e.NewValue;
_sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
_sensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
_sensor.DepthFrameReady += new EventHandler<DepthImageFrameReadyEventArgs>(_sensor_DepthFrameReady);
_sensor.ColorFrameReady += new EventHandler<ColorImageFrameReadyEventArgs>(_sensor_ColorFrameReady);
_sensor.DepthStream.FrameHeight);
try
{
_sensor.Start();
}
catch
{
kinectSensorChooser.AppConflictOccurred();
}
}
void KinectStop(KinectSensor sensor)
{
if (sensor != null)
{
sensor.Stop();
}
}
private void Window_Closed(object sender, EventArgs e)
{
KinectStop(kinectSensorChooser.Kinect);
}
void _sensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
{
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
if (colorFrame == null) return;
if (first)
{
this.colorPixels = new Byte[colorFrame.PixelDataLength];
first = false;
}
colorFrame.CopyPixelDataTo(this.colorPixels); //raw data in bgrx format
processColor();
}
}
void _sensor_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame == null) return;
if (firstDepth)
{
this.rawDepthData = new short[depthFrame.PixelDataLength];
firstDepth = false;
}
depthFrame.CopyPixelDataTo(rawDepthData);
processDepth();
}
}
private void processColor(){...}
private void processDepth(){...}
}
}
The processDepth function is as follows. I am just making an Image from the RAW depth data.
private void processDepth() {
GCHandle pinnedArray = GCHandle.Alloc(this.rawDepthData, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
cvDepthImage = new Image<Gray, Int16>(depthWidth, depthHeight, depthWidth << 1, pointer);
pinnedArray.Free();
depthImage.Source = BitmapSourceConvert.ToBitmapSource(cvDepthImage.Not().Bitmap);
}
The processColor function is as follows. Here just for the sake of it, I am trying to display the cloned image instead of extracting features, just to check the lag. When both streams are enabled (color and depth) the following function displays the colorImage properly, but as soon as I uncomment the commented lines, the UI hangs.
private void processColor() {
GCHandle handle = GCHandle.Alloc(this.colorPixels, GCHandleType.Pinned);
Bitmap image = new Bitmap(colorWidth, colorHeight, colorWidth<<2, System.Drawing.Imaging.PixelFormat.Format32bppRgb, handle.AddrOfPinnedObject());
handle.Free();
cvColorImage = new Image<Bgra, byte>(image);
image.Dispose();
BitmapSource src = BitmapSourceConvert.ToBitmapSource(cvColorImage.Bitmap);
colorImage.Source = src;
//image2 = new Image<Bgra, byte>(cvColorImage.ToBitmap()); //uncomment and it hangs
//featureImage1.Source = BitmapSourceConvert.ToBitmapSource(image2.Bitmap); //uncomment and it hangs
}
I see code that do a lot of work in event handlers. I almost certain that handlers is called in GUI thread. I suggest you to extract your code to the background thread routine. Don't forget that updating of the Form's controls (depthImage and controlImage) should be done using BeginInvoke method of the parent form,

Categories

Resources