I need help C# and Emgu cv - c#

I am developing a simple application on face recognition using EmguCv and c#. i am using ms access data to store sample data base. whenever in compile the code i get error "OpenCV: Different sizes of objects" Here is my code.... thanks in ADVANCE.
public partial class Facerecognition : Form
{
EigenObjectRecognizer Recognizer;
private Capture cam;
Image<Bgr, Byte> frame;
Image<Gray, Byte> frame2;
private HaarCascade Haar;
MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_TRIPLEX, 0.5d, 0.5d);
OleDbConnection Connection = new OleDbConnection();
OleDbDataAdapter Adapter;
DataTable Table = new DataTable();
List<string> FaceName = new List<string>();
List<Image<Gray, byte>> FaceImg = new List<Image<Gray, byte>>();
int ConTrain;
string name;
Image result;
public Facerecognition()
{
InitializeComponent();
Haar = new HaarCascade("haarcascade_frontalface_default.xml");
ConnectDatabase();
}
private void button3_Click(object sender, EventArgs e)
{
Traningset t = new Traningset();
t.Show();
}
public void Process(object sender, EventArgs e)
{
frame = cam.QueryFrame();
LoadRecognizer();
pictureBox1.Image = frame.ToBitmap();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void button2_Click(object sender, EventArgs e)
{
cam = new Capture();
Application.Idle += Process;
}
/*public void FaceDetection()
{
frame2 = frame.Convert<Gray, Byte>();
var faces = frame.DetectHaarCascade(Haar, 1.2, 3, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(25, 25))[0];
foreach (var face in faces)
{
frame.Draw(face.rect, new Bgr(Color.Black), 3);
// MessageBox.Show("Face detected " + faces.Length.ToString());
}
}*/
public void ConnectDatabase()
{
Connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=facedatabase.mdb.mdb";
Adapter = new OleDbDataAdapter("Select facename, faceimg from traningset", Connection);
OleDbCommandBuilder CommandBuilder = new OleDbCommandBuilder(Adapter);
Adapter.Fill(Table);
Connection.Open();
if (Table.Rows.Count != 0)
{
int numofrows = Table.Rows.Count;
}
Connection.Close();
}
public Image GetFaceFromDB()
{
Image Fetehedimg;
byte[] fetechedimgbytes = (byte[])Table.Rows[0]["faceimg"];
MemoryStream stream = new MemoryStream(fetechedimgbytes);
Fetehedimg = Image.FromStream(stream);
return Fetehedimg;
}
public void LoadRecognizer()
{
/////////////////////////////////////////////// FACE DETECTER /////////////////////////////////////////////////////
frame2 = frame.Convert<Gray, Byte>();
var faces = frame.DetectHaarCascade(Haar, 1.2, 3, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(25, 25))[0];
foreach (var face in faces)
{
frame.Draw(face.rect, new Bgr(Color.Black), 3);
// MessageBox.Show("Face detected " + faces.Length.ToString());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ConnectDatabase();
Bitmap bitimage;
Image img;
img = new Bitmap(100, 100);
int numofrows=0;
if(Table.Rows.Count!=0)
{
numofrows=Table.Rows.Count;
}
for (int i = 0; i < numofrows; i++)
{
byte[] fetchedBytes = (byte[])Table.Rows[i]["faceimg"];
MemoryStream stream = new MemoryStream(fetchedBytes);
bitimage = new Bitmap(stream);
//bitimage = bitimage.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
FaceImg.Add(new Emgu.CV.Image<Gray, Byte>(bitimage));
String faceName = (String)Table.Rows[i]["facename"];
FaceName.Add(faceName);
}
if (FaceImg.ToArray().Length != 0)
{
MCvTermCriteria termCrit = new MCvTermCriteria(4, 0.001);
Recognizer = new EigenObjectRecognizer(
FaceImg.ToArray(),
FaceName.ToArray(),
3000,
ref termCrit);
MessageBox.Show("face recognized");
// frame.Draw(name, ref font, new Point(faces.rect.X - 2, faces.rect.Y - 2), new Bgr(Color.LightGreen));
}
}
}
}

Uncomment Resize:
for (int i = 0; i < numofrows; i++)
{
byte[] fetchedBytes = (byte[])Table.Rows[i]["faceimg"];
MemoryStream stream = new MemoryStream(fetchedBytes);
bitimage = new Bitmap(stream);
Image<Gray, byte> img = new Emgu.CV.Image<Gray, Byte>(bitimage )
Image<Gray, byte> resizedImage = img.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
FaceImg.Add(resizedImage);
String faceName = (String)Table.Rows[i]["facename"];
FaceName.Add(faceName);
}
You can't perform in Resize in place, that's why the uncommented line was giving you another error:
// not allowed
bitimage = bitimage.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

Related

how to load cropping image to picturebox c#

Here is my small software.. We add images clicking "ADD YOUR QR CODE" and it will be displayed on pictureBoxLoad picturebox, After that i will crop the image. Then it shows on picturebox2.
But my problem is ,it is only shows on picturebox2, But picturebox2.image is null...how to fix that error. I want to add cropping image to picturebox2 without null..
here after clicking the crop button
here is the code i tried
{
int xDown = 0;
int yDown = 0;
int xUp = 0;
int yUp = 0;
Rectangle rectCropArea = new Rectangle();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Task timeout;
string fn = "";
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
}
private void selectIm_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void PictureBoxLoad_MouseUp(object sender, MouseEventArgs e)
{
}
private void PictureBoxLoad_MouseDown(object sender, MouseEventArgs e)
{
}
private void crop_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter= "Image Files(*.jpg; *.jpeg; *.gif;*.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp;*.png";
if (opf.ShowDialog() == DialogResult.OK)
{
PictureBoxLoad.Image = Image.FromFile(opf.FileName);
fn = opf.FileName;
}
PictureBoxLoad.Cursor = Cursors.Cross;
}
private void button2_Click(object sender, EventArgs e)
{
string root = #"C:\FuePass";
// If directory does not exist, create it.
if (!System.IO.Directory.Exists(root))
{
System.IO.Directory.CreateDirectory(root);
}
Bitmap bmp = new Bitmap(previewimg.Width, previewimg.Height);
previewimg.DrawToBitmap(bmp, new Rectangle(0, 0, previewimg.Width, previewimg.Height));
pictureBox2.DrawToBitmap(bmp, new Rectangle(pictureBox2.Location.X - previewimg.Location.X, pictureBox2.Location.Y - previewimg.Location.Y, pictureBox2.Width, pictureBox2.Height));
bmp.Save(#"C:\Fuepass\output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
MessageBox.Show("Saved,Locaiton : C:\\Fuepass\\");
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = "JPG(*.JPG)|*.jpg";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// previewimg.Image.Save(dialog.FileName);
// pictureBox2.Image.Save(dialog.FileName);
// }
// }
}
private void PictureBoxLoad_Click(object sender, EventArgs e)
{
}
private void PictureBoxLoad_MouseDown_1(object sender, MouseEventArgs e)
{
PictureBoxLoad.Invalidate();
xDown = e.X;
yDown = e.Y;
crop.Enabled = true;
}
private void PictureBoxLoad_MouseUp_1(object sender, MouseEventArgs e)
{
//pictureBox1.Image.Clone();
xUp = e.X;
yUp = e.Y;
Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
using (Pen pen = new Pen(Color.YellowGreen, 3))
{
PictureBoxLoad.CreateGraphics().DrawRectangle(pen, rec);
}
rectCropArea = rec;
crop.Enabled = true;
}
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
//pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}
}
}
plz tell me the error
You should be able to set the Image to a Bitmap. But do not dispose the Bitmap before you do the save. Hope this helps.
private void crop_Click_1(object sender, EventArgs e)
{
try
{
pictureBox2.Refresh();
//Prepare a new Bitmap on which the cropped image will be drawn
Bitmap sourceBitmap = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Graphics g = pictureBox2.CreateGraphics();
//Draw the image on the Graphics object with the new dimesions
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
crop.Enabled = false;
var path = Environment.CurrentDirectory.ToString();
ms = new System.IO.MemoryStream();
pictureBox2.Image = sourceBitmap;
pictureBox2.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] ar = new byte[ms.Length];
var timeout = ms.WriteAsync(ar, 0, ar.Length);
sourceBitmap.Dispose();
}
catch (Exception ex)
{
}
if (pictureBox2.Image == null)
{
MessageBox.Show("no image");
}
}

How to get the real size of the image in image list

I have a piece of code which shows the pictures in a specific size. I want to get the real size of the pictures and want to show those pictures in their real size.
Can anybody help me in this matter.
Here is the piece of code which I am using to get the pictures.
private void btnZoom_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
string[] pics = System.IO.Directory.GetFiles("TestFolder//");
listView1.View = View.SmallIcon;
listView1.SmallImageList = imageList1;
imageList1.ImageSize = new Size(64, 64);
foreach (string pic in pics)
{
imageList1.Images.Add(Image.FromFile(pic));
}
for (int j = 0; j < imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
listView1.Items.Add(item);
}
}
It's a Windows Form App.
Here's another approach...store the Image and its Full Path FileName in the Tag property of your ListViewItem using a Tuple<Image, String>.
Something like:
private void btnZoom_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
imageList1.Images.Clear();
string[] pics = System.IO.Directory.GetFiles(#"C:\Users\mikes\Pictures\Facebook\Backyard Wildlife"); //"TestFolder//");
listView1.View = View.SmallIcon;
listView1.SmallImageList = imageList1;
imageList1.ImageSize = new Size(64, 64);
for(int i = 0; i < pics.Length; i++)
{
Image img;
using (FileStream fs = new FileStream(pics[i], FileMode.Open))
{
try
{
img = Image.FromStream(fs);
imageList1.Images.Add(img);
ListViewItem item = new ListViewItem();
item.ImageIndex = imageList1.Images.Count - 1;
item.Text = System.IO.Path.GetFileNameWithoutExtension(pics[i]);
item.Tag = new Tuple<Image, String>(img, pics[i]);
listView1.Items.Add(item);
}
catch (Exception ex) { };
}
}
}
private void btnView_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
Tuple<Image, String> data = (Tuple < Image, String >)item.Tag;
label1.Text = data.Item2;
pictureBox1.Image = data.Item1;
Size sz = data.Item1.Size;
label2.Text = sz.ToString();
}
}

Can't open video picturebox using Opencv library

I can't open video in picturebox My code is:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.FileName = "*.*";
if (open.ShowDialog() == DialogResult.OK)
{
isAnyText = false;
// string text = open.FileName;
// MessageBox.Show("resimin yolu :" + text);
/// CvVideoWriter video = new CvVideoWriter();
// videoSource.NewFrame += new NewFrameEventHan
CvCapture capture = new CvCapture(open.FileName);
pictureBox1.Image = new Bitmap(capture);
// pictureBox1.Image = capture;// new Bitmap(pictureBox1.Image);
//pictureBox1.Capture = new Bitmap(open.FileName);
// pictureBox1.Image.
string plaka = ft.GetImageText(open.FileName);
var img = pictureBox1.Image;
}
foreach (var s in ft.textList)
listBox1.Items.Add(s);
}
I have a problem here
pictureBox1.Image = new Bitmap(capture);
At the same time I try this:
pictureBox1.Capture = new Bitmap(open.FileName);
and I try lots of things but I cant do it
Any advance?

Argument Exception while converting byte array to image

I convert Image to byte[] using this code (Form.cs):
private void button1_Click(object sender, EventArgs e)
{
Form1 fom = new Form1();
ImageConverter converter = new ImageConverter();
byte[] imgArray = (byte[])converter.ConvertTo(fom.panel1.BackgroundImage, typeof(byte[]));
ImageData img = new ImageData
{
ClassName = textBox1.Text,
Password = textBox2.Text,
Image = imgArray,
};
using (BoardDatabaseEntities dc = new BoardDatabaseEntities())
{
dc.ImageDatas.Add(img);
dc.SaveChanges();
MessageBox.Show("Saved into database");
}
this.Close();
}
Then, I am trying to convert it back to Image::
protected void Button1_Click(object sender, EventArgs e)
{
using (BoardDatabaseEntities dc = new BoardDatabaseEntities())
{
var v = dc.ImageDatas.Where(a => a.ClassName.Equals(TextBox3.Text) && a.Password.Equals(TextBox4.Text)).FirstOrDefault();
if (v != null)
{
byte[] byt = v.Image;
ImageConverter ic = new ImageConverter();
System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(byt);
String name = v.ClassName;
try
{
var ratio = (double)100 / img.Height;
int imageHeight = (int)(img.Height * ratio);
int imageWidth = (int)(img.Width * ratio);
System.Drawing.Image.GetThumbnailImageAbort dCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image thumbnailImg = img.GetThumbnailImage(imageWidth, imageHeight, dCallback, IntPtr.Zero);
thumbnailImg.Save(Path.Combine(Server.MapPath("~/Thumbnail"), name), ImageFormat.Jpeg);
thumbnailImg.Dispose();
//Here Code for Get Uploaded Images
PopulateImage();
}
catch (Exception ex)
{
throw;
}
}
}
}
It is giving me an ArgumentException Error in line:
System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(byt);
It says, parameter is invalid.

c# A generic error occurred in GDI+

I have this problem when I drag to select region of the image in the picturebox more than two times and run the scanning. This is an OCR system.
region OCR(Tab4_Component)
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");
singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//bw.RunWorkerAsync(bw);
//bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 70)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
for (int i = 0; i < 1; i++)
{
string getText = rd2["Character"].ToString();
Action showText = () => ocrTB.AppendText(getText);
ocrTB.Invoke(showText);
}
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
i understand the reason it occur is that the image has been duplicated. But I have no idea how to solve it.
First off this looks like a dublicate of this topic:
c# Bitmap.Save A generic error occurred in GDI+ windows application
You also authored that question. From what I can tell it's the same question regarding the same code.
You mention this happens the second time you select an area, and both time you save the image to the same path. You also say the errors occurs when saving.
I think that would be a very strong indication of a permission error. Have you tried saving to a new file name every time as a test?
If it's a permission error then you simply need to dispose of any resources that have taken a lock on that file.
There are plenty of examples of this out there:
http://www.kerrywong.com/2007/11/15/understanding-a-generic-error-occurred-in-gdi-error/
public void Method1()
{
Image img = Image.FromFile(fileName);
Bitmap bmp = img as Bitmap;
Graphics g = Graphics.FromImage(bmp);
Bitmap bmpNew = new Bitmap(bmp);
g.DrawImage(bmpNew, new Point(0, 0));
g.Dispose();
bmp.Dispose();
img.Dispose();
//code to manipulate bmpNew goes here.
bmpNew.Save(fileName);
}
There could however be other issues. If you get the image from a stream, this stream needs to remain open until you're done with the image. (When you dispose of the image you'll automatically dispose of the stream.)
I can't see anything like that in the code you've posted though.
If you are using a 3rd party library for the OCR part, it could also have taken a lock on the resource.
A good place to read about this would be here:
http://support.microsoft.com/?id=814675
However from all you've said it simply sounds like there's a lock on the file you try to save to. So as mentioned above I would start off by simply trying to give the file a new name each time. If it doesn't work then you can start exploring other possibilities.
Quick and dirty example:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic-" + Guid.NewGuid().ToString() + #".jpg");
You should try this before dismissing a permission issue.

Categories

Resources