I am able to convert the emgu image format to a byte string and this does save on the MySQL database with this code, but the image is saved in a format not even recognized by windows image viewer
string myConnection = mydbconnection;
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
Bitmap image = trained.ToBitmap();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] picture = ms.ToArray();
string formmattedPic = Convert.ToBase64String(picture);
MySqlCommand cmd = new MySqlCommand("INSERT INTO sql434250.facialid (timeanddate,photo1) VALUES(#named,#Trainedface)",myConn);
cmd.Parameters.Add("#named", MySqlDbType.VarChar).Value = named;
cmd.Parameters.Add("#Trainedface", MySqlDbType.Blob);
cmd.Parameters["#Trainedface"].Value = formmattedPic;
cmd.ExecuteNonQuery();
label4.Text = named.ToString();
myConn.Close();
}
My problem starts when I try to add the final image formatting I get a system not supported exception on the fs = new FileStream(named, FileMode.Open, FileAccess.Read); line, I am not sure how the filestream works, (new to C#) so please forgive me for any obvious mistakes in the code, for information I am on a windows 8 os, vs 2013
as here:
FileStream fs;
BinaryReader br;
byte[] ImageData;
**fs = new FileStream(named, FileMode.Open, FileAccess.Read);**
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
MySqlCommand cmd = new MySqlCommand("INSERT INTO sql434250.facialid (timeanddate,photo1) VALUES(#named,#Trainedface)",myConn);
cmd.Parameters.Add("#named", MySqlDbType.VarChar).Value = named;
cmd.Parameters.Add("#Trainedface", MySqlDbType.Blob);
cmd.Parameters["#Trainedface"].Value = ImageData;
cmd.ExecuteNonQuery();
I am able to take converted images saved on my pc and manually download via the MySQL site the images these images do work with the software, so to my shame I know its a coding error.
added database table as follows:
CREATE TABLE `**yourdatabase**`.`facialid` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT ,
`timeanddate` varchar( 30 ) NOT NULL ,
`photo1` longblob NOT NULL ,
`code1` varchar( 50 ) NOT NULL ,
`code2` varchar( 50 ) NOT NULL ,
`code3` varchar( 50 ) NOT NULL ,
PRIMARY KEY ( `id` )
added full form code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.IO;
using System.Diagnostics;
using MySql.Data.MySqlClient;
using System.Drawing.Imaging;
namespace MultiFaceRec
{
public partial class FrmPrincipal : Form
{
//Declararation of all variables, vectors and haarcascades
Image<Bgr, Byte> currentFrame;
Capture grabber;
HaarCascade face;
HaarCascade eye;
MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_TRIPLEX, 0.5d, 0.5d);
Image<Gray, byte> result, TrainedFace = null;
Image<Gray, byte> gray = null;
Image<Gray, byte> trained = null;
Image image1 = null;
List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
List<string> labels= new List<string>();
List<string> NamePersons = new List<string>();
int ContTrain, t;
string name, names = null;
public FrmPrincipal()
{
InitializeComponent();
//Load haarcascades for face detection
face = new HaarCascade("haarcascade_frontalface_default.xml");
//eye = new HaarCascade("haarcascade_eye.xml");
}
public void dbconnection()
{
grabber = new Capture();
grabber.QueryFrame();
//Initialize the FrameGraber event
Application.Idle += new EventHandler(FrameGrabber);
try
{
//Load of previus trainned faces and labels for each image
string myConnection = **"youdbconnection"**
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlDataAdapter myAdapter = new MySqlDataAdapter();
int totalrows = 0;
int rownumber = 0;
MySqlCommand SelectCommand = new MySqlCommand(" select * from **yourdb**.facialid ", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
string id = myReader.GetString("id");
string Labelsinfo = myReader.GetString("timeanddate");
string picdata = myReader.GetString("photo1");
string LoadFaces;
LoadFaces = myReader.GetString("photo1");
byte[] picData = myReader["photo1"] as byte[] ?? null;
ImageConverter pic = new ImageConverter();
Image img = (Image)pic.ConvertFrom(myReader["photo1"]);
Bitmap bitmap1 = new Bitmap(img);
trainingImages.Add(new Image<Gray, byte> (bitmap1));
labels.Add(Labelsinfo);
rownumber = count +1;
totalrows = count;
ContTrain = count;
//string userid = myReader.GetString("id");
//string useron = myReader.GetString("user");
}
myReader.Close();
myConn.Close();
label2.Text = totalrows.ToString();
}
catch(MySqlException ex)
{
//MessageBox.Show(e.ToString());
int errorcode = ex.Number;
MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void button2_Click(object sender, System.EventArgs e)
{
try
{
//Trained face counter
ContTrain = ContTrain + 1;
//Get a gray frame from capture device
gray = grabber.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//Face Detector
MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
face,
1.2,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20));
//Action for each element detected
foreach (MCvAvgComp f in facesDetected[0])
{
trained = currentFrame.Copy(f.rect).Convert<Gray, byte>();
TrainedFace = currentFrame.Copy(f.rect).Convert<Gray, byte>();
break;
}
//resize face detected image for force to compare the same size with the
//test image with cubic interpolation type method
TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//string image;
//Show face added in gray scale
imageBox1.Image = TrainedFace;
string named = DateTime.Now.ToString("dd-MM-yy HH:mm:ss:ms");
string myConnection = **"your db connection"**
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
Bitmap image = trained.ToBitmap();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] picture = ms.ToArray();
string formmattedPic = Convert.ToBase64String(picture);
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(named, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
MySqlCommand cmd = new MySqlCommand("INSERT INTO **yourdb**.facialid (timeanddate,photo1) VALUES(#named,#Trainedface)",myConn);
cmd.Parameters.Add("#named", MySqlDbType.VarChar).Value = named;
cmd.Parameters.Add("#Trainedface", MySqlDbType.Blob);
cmd.Parameters["#Trainedface"].Value = ImageData;
cmd.ExecuteNonQuery();
label4.Text = named.ToString();
myConn.Close();
}
catch (MySqlException ee)
{
int errorcode = ee.Number;
}
}
void FrameGrabber(object sender, EventArgs e)
{
label3.Text = "0";
//label4.Text = "";
NamePersons.Add("");
//Get the current frame form capture device
currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//Convert it to Grayscale
gray = currentFrame.Convert<Gray, Byte>();
//Face Detector
MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
face,
1.2,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20));
//Action for each element detected
foreach (MCvAvgComp f in facesDetected[0])
{
t = t + 1;
result = currentFrame.Copy(f.rect).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//draw the face detected in the 0th (gray) channel with blue color
currentFrame.Draw(f.rect, new Bgr(Color.Red), 2);
if (trainingImages.ToArray().Length != 0)
{
//TermCriteria for face recognition with numbers of trained images like maxIteration
MCvTermCriteria termCrit = new MCvTermCriteria(ContTrain, 0.001);
//Eigen face recognizer
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
trainingImages.ToArray(),
labels.ToArray(),
1000,
ref termCrit);
name = recognizer.Recognize(result);
//Draw the label for each face detected and recognized
currentFrame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.LightGreen));
}
NamePersons[t-1] = name;
NamePersons.Add("");
//Set the number of faces detected on the scene
label3.Text = facesDetected[0].Length.ToString();
/*
//Set the region of interest on the faces
gray.ROI = f.rect;
MCvAvgComp[][] eyesDetected = gray.DetectHaarCascade(
eye,
1.1,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20));
gray.ROI = Rectangle.Empty;
foreach (MCvAvgComp ey in eyesDetected[0])
{
Rectangle eyeRect = ey.rect;
eyeRect.Offset(f.rect.X, f.rect.Y);
currentFrame.Draw(eyeRect, new Bgr(Color.Blue), 2);
}
*/
}
t = 0;
//Names concatenation of persons recognized
for (int nnn = 0; nnn < facesDetected[0].Length; nnn++)
{
names = names + NamePersons[nnn] + ", ";
}
//Show the faces procesed and recognized
imageBoxFrameGrabber.Image = currentFrame;
//Clear the list(vector) of names
NamePersons.Clear();
}
private void FrmPrincipal_Load(object sender, EventArgs e)
{
dbconnection();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
I was able to solve my question, I don't know what I did wrong but with a little copying here and there the following code works, what I have done is first stored the image to a local application file and used this file location in the file stream.
named = DateTime.Now.ToString("dd-MM-yy HH:mm:ss:ms");
TrainedFace.Save(Application.StartupPath + "/Temp/face1.bmp");
string dated = DateTime.Now.ToString("HH:mm:ss:ff dd-MM-yy");
label4.Text = dated;
//Show face added in gray scale
imageBox1.Image = TrainedFace;
trainingImages.Add(TrainedFace);
labels.Add(label4.Text);
byte[] imagepic = null;
FileStream fsstream = new FileStream(Application.StartupPath + "/Temp/face1.bmp", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fsstream);
imagepic = br.ReadBytes((int)fsstream.Length);
string myConnection = "datasource=sql4.freemysqlhosting.net;port=3306;user=sql434250;password=lE3!lQ5*";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("INSERT INTO `sql434250`.`facialid` (`id`, `timeanddate`, `photo1`) VALUES (NULL, #dated, #IMG);", myConn);
MySqlDataReader myReader;
myConn.Open();
SelectCommand.Parameters.Add(new MySqlParameter("#IMG", imagepic));
SelectCommand.Parameters.Add(new MySqlParameter("#dated", dated));
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
}
Related
I have project code to create a face recognition system using EMGUCV. I have trained the database with 2 people. When the webcam detects those people and able to show the name correctly but the problem is the third person whose do not exist in trained database detect by webcam, it will take the nearest face and display the name on it instead of show "Unknown". How can I improve the accuracy? I have tried to change the threshold value but didn't help. What's going wrong?
MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_TRIPLEX, 0.6d, 0.6d);
HaarCascade faceDetected;
Image<Bgr, Byte> Frame;
Capture camera;
Image<Gray, byte> result;
Image<Gray, byte> TrainedFace = null;
Image<Gray, byte> grayFace = null;
List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
List<string> labels = new List<string>();
List<string> Users = new List<string>();
EigenObjectRecognizer recognizer;
int Count, NumLabels, t;
string name, names = null;
public Form1()
{
InitializeComponent();
PhotoPers.Image = Properties.Resources.EmptyPiC;
//HaarCascade is for face detection
faceDetected = new HaarCascade("haarcascade_frontalface_default.xml");
try
{
string Labelsinfo = File.ReadAllText(Application.StartupPath + "/Faces/Faces.txt");
string[] Labels = Labelsinfo.Split(',');
NumLabels = Convert.ToInt16(Labels[0]);
Count = NumLabels;
string LoadFaces;
// if (result)
// {
// CvInvoke.cvPutText(Frame, name[result.Labels], new Point(face.X - 2, face.Y - 2),
// FontFace.HersheyComplex, 1.0, new Bgr(Color.Orange).MCvScalar);
// CvInvoke.cvRectangle(Frame, face, new Bgr(Color.Green).MCvScalar, 2);
//}
for (int tf = 1; tf < NumLabels + 1; tf++)
{
LoadFaces = "face" + tf + ".bmp";
trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "/Faces/" + LoadFaces));
labels.Add(Labels[tf]);
}
}
catch (Exception e)
{
}
}
string imgLocation = " ";
private void button1_Click(object sender, EventArgs e)
{
camera = new Capture();
camera.QueryFrame();
Application.Idle += new EventHandler(FrameProcedure);
}
private void BtnSave_Click(object sender, EventArgs e)
{
byte[] images = null;
FileStream Streem = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
BinaryReader brs = new BinaryReader(Streem);
images = brs.ReadBytes((int)Streem.Length);
if (txtName.Text == "" || txtLName.Text == " " || txtIDNo.Text == " " || cboDepartment.Text == " ")
{
MessageBox.Show("All fields must be fillup!");
}
else
{
Count = Count + 1;
grayFace = camera.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
MCvAvgComp[][] DetectedFaces = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in DetectedFaces[0])
{
TrainedFace = Frame.Copy(f.rect).Convert<Gray, byte>();
break;
}
TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
trainingImages.Add(TrainedFace);
labels.Add(txtName.Text);
File.WriteAllText(Application.StartupPath + "/Faces/Faces.txt", trainingImages.ToArray().Length.ToString() + ",");
for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
{
trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/Faces/face" + i + ".bmp");
File.AppendAllText(Application.StartupPath + "/Faces/Faces.txt", labels.ToArray()[i - 1] + ",");
}
}
mCon.ConOpen();
string SaveStr = "INSERT INTO tblRegister (FirstName, LastName, IDno, Department, Image)" +
"VALUES(#FirstName, #LastName, #IDno, #Department, #Image)";
SqlCommand myCommand = new SqlCommand(SaveStr, mCon.myCon);
myCommand.Parameters.AddWithValue("#FirstName", txtName.Text);
myCommand.Parameters.AddWithValue("#LastName", txtLName.Text);
myCommand.Parameters.AddWithValue("#IDno", txtIDNo.Text);
myCommand.Parameters.AddWithValue("#Department", cboDepartment.Text);
myCommand.Parameters.AddWithValue("#Image", images);
myCommand.ExecuteNonQuery();
mCon.ConClose();
MessageBox.Show("Data has been Save!");
txtName.Text = " ";
txtLName.Text = " ";
txtIDNo.Text = " ";
cboDepartment.Text = " ";
}
private void PhotoPers_Click(object sender, EventArgs e)
{
}
private void FrameProcedure(object sender, EventArgs e)
{
Users.Add("");
Frame = camera.QueryFrame().Resize(500, 300, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
grayFace = Frame.Convert<Gray, Byte>();
MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in facesDetectedNow[0])
{
result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
Frame.Draw(f.rect, new Bgr(Color.Cyan), 3);
if (trainingImages.ToArray().Length != 0)
{
MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 4500, ref termCriterias);
name = recognizer.Recognize(result);
Frame.Draw(string.IsNullOrEmpty(name) ? "UNKNOWN" : name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
Users.Add("");
}
CameraBox.Image = Frame;
names = "";
Users.Clear();
}
private void TrainImagesFromDir()
{
//string path = Directory.GetCurrentDirectory() + "/Faces/Faces.txt";
//Users.Add("");
//Frame = camera.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//grayFace = Frame.Convert<Gray, Byte>();
//MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
//foreach (MCvAvgComp f in facesDetectedNow[1])
//{
// result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
// Frame.Draw(f.rect, new Bgr(Color.Green), 3);
// if (trainingImages.ToArray().Length != 0)
// {
// MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
// EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 1500, ref termCriterias);
// name = recognizer.Recognize(result);
// Frame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
private void btnUpload_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "png files(*.png)|*.png|jpg files(*.jpg)|*.jpg|All files (*.*)|*.*";
if (dialog.ShowDialog() == DialogResult.OK)
{
imgLocation = dialog.FileName.ToString();
PhotoPers.ImageLocation = imgLocation;
}
}
}
This is my update button click event:
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (ValidateAll())
{
SetValues();
_objHotel_EL.HotelID = HotelId;
_objHotel_EL.CommandName = "Update_HotelDetails";
int update = _objHotel_BL.Insert_Hotel(_objHotel_EL);
if (update > 0)
{
MessageBox.Show("Hotel Details Updated");
ClearAll();
}
else
{
MessageBox.Show("Already Exists");
ClearAll();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here's my code which is used to set and upload image and other parameters:
private void SetValues()
{
_objHotel_EL.HotelName = txtHotelName.Text.Trim();
_objHotel_EL.PhoneNo = txtPhoneNo.Text.Trim();
_objHotel_EL.Address = txtAddress.Text.Trim();
_objHotel_EL.EmailId = txtEmailId.Text.Trim();
_objHotel_EL.WebSite = txtWebsite.Text.Trim();
_objHotel_EL.CurrID = CommanValue.CurrID;
if (flag == 1)
{
_objHotel_EL.BinaryImage = ReadFile(labelImagePath.Text);
_objHotel_EL.ImagePath = labelImagePath.Text;
}
else
{
if (imageData == null)
{
string path = System.AppDomain.CurrentDomain.BaseDirectory.Replace("\\Debug", "");
path = path.Replace("\\bin", "");
path = path.Replace("\\x86", "");
path = path + "Images\\NoImage1.png";
labelImagePath.Text = path;
imageData = ReadFile(labelImagePath.Text);
_objHotel_EL.ImagePath = path;
}
_objHotel_EL.ImagePath = labelImagePath.Text;
_objHotel_EL.BinaryImage = (byte[])imageData;
}
}
This is code of ReadFile:
private byte[] ReadFile(string strPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(strPath);
long numBytes = fInfo.Length;
FileStream fstream = new FileStream(strPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
data = br.ReadBytes((int)numBytes);
return data;
}
Please help me out because its giving me an error The conversion is not supported. [ Type to convert from (if known) = nvarchar, Type to convert to (if known) = image ] while i am using sql server compact in visual studio 2012 using c#.
In database side datatype of image is image.
Actually I tried with myself after using SqlCeCommand parameters and its solved.
Here is the code.
if (objEL.CommandName == "Update_HotelDetails")
{
DataTable dt = SqlHelper.ExecuteDataset("SELECT HotelName, HotelID FROM Master_Hotel WHERE (HotelName = '" + objEL.HotelName + "') AND (HotelID <> '" + objEL.HotelID + "')").Tables[0];
if (dt.Rows.Count == 0)
{
string str = ("UPDATE Master_Hotel SET HotelName = #HotelName, PhoneNo = #PhoneNo, Address = #Address, EmailId = #EmailId, Website = #Website, Image = #Image,ImagePath = #ImagePath WHERE (HotelID = #HotelID)");
cmd = new SqlCeCommand(str, SqlHelper.objCon);
cmd.Parameters.Add("#HotelName", SqlDbType.NVarChar).Value = objEL.HotelName;
cmd.Parameters.Add("#PhoneNo", SqlDbType.NVarChar).Value = objEL.PhoneNo;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar).Value = objEL.Address;
cmd.Parameters.Add("#EmailId", SqlDbType.NVarChar).Value = objEL.EmailId;
cmd.Parameters.Add("#Website", SqlDbType.NVarChar).Value = objEL.WebSite;
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = objEL.BinaryImage;
cmd.Parameters.Add("#ImagePath", SqlDbType.NVarChar).Value = objEL.ImagePath;
cmd.Parameters.Add("#HotelID", SqlDbType.Int).Value = objEL.HotelID;
SqlHelper.objCon.Open();
i = cmd.ExecuteNonQuery();
SqlHelper.objCon.Close();
}
}
I have two IP cameras. I want to run both of them simultaneously. I am using Emgu CV to process images. So here, when I click Start button, my program will check which my cameras are active (get their IP addresses). After getting their IP addresses, my program will use those IPs to get data from database. The condition that I get, my program will be very slow and there is delay for several seconds when capture process is running. Can anyone help me what I must do to solve this problem ? Here what I have done
private void Tombol_Start_Click(object sender, EventArgs e)
{
ProsesSemuaKamera();
}
private void ProsesSemuaKamera()
{
Ping ping = new Ping();
PingReply pingreply;
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
kon.Open();
string selecturl = "select * from datakamera";
command.CommandText = selecturl;
OleDbDataReader bacadata = command.ExecuteReader();
while (bacadata.Read())
{
int counturl = 0;
pingreply = ping.Send(bacadata["ipadd"].ToString());
if (pingreply.Status == IPStatus.Success)
{
listBox1.Items.Add(bacadata["namakamera"].ToString());
CaptureSemuaKamera = new Capture(bacadata["urlkamera"].ToString());
Application.Idle += new EventHandler(ProcessFrameSemuaKamera);
}
else if (pingreply.Status != IPStatus.Success)
{
textBox3.Text += bacadata["namakamera"].ToString() + Environment.NewLine;
}
}
kon.Close();
}
private void ProcessFrameSemuaKamera(object sender, EventArgs e)
{
Image<Bgr, Byte> sourceImage = CaptureSemuaKamera.QueryFrame();
SourceBox.Image = sourceImage.Bitmap;
ProsesKameraSemua();
}
private string BuildWhereClause(ListBox lb)
{
string WHEREclause = string.Empty;
foreach (string itm in lb.Items)
{
if (WHEREclause == string.Empty)
{
WHEREclause += " where namakamera = '" + itm + "' ";
}
else
{
WHEREclause += " OR namakamera = '" + itm + "' ";
}
}
return WHEREclause;
}
private void ProsesKameraSemua()
{
Image<Bgr, Byte> sourceImage = CaptureSemuaKamera.QueryFrame();
SourceBox.Image = sourceImage.Bitmap;
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand commandkoord = kon.CreateCommand();
OleDbCommand commandkoordgaris = kon.CreateCommand();
kon.Open();
string selectsemuakoord = "select * from koordinatkotak " + BuildWhereClause(listBox1);
string selectsemuakoordgaris = "select * from koordinatgaris " + BuildWhereClause(listBox1);
commandkoord.CommandText = selectsemuakoord;
commandkoordgaris.CommandText = selectsemuakoordgaris;
OleDbDataReader bacakoord = commandkoord.ExecuteReader();
OleDbDataReader bacakoordgaris = commandkoordgaris.ExecuteReader();
while (bacakoord.Read() && bacakoordgaris.Read())
{
#region Perspective projection
PointF[] srcs = new PointF[4];
srcs[0] = new PointF(int.Parse(bacakoord["x1source"].ToString()), int.Parse(bacakoord["y1source"].ToString())); //119, 187
srcs[1] = new PointF(int.Parse(bacakoord["x2source"].ToString()), int.Parse(bacakoord["y2source"].ToString())); //242, 181
srcs[2] = new PointF(int.Parse(bacakoord["x3source"].ToString()), int.Parse(bacakoord["y3source"].ToString())); //253, 225
srcs[3] = new PointF(int.Parse(bacakoord["x4source"].ToString()), int.Parse(bacakoord["y4source"].ToString())); //112, 231
PointF[] dsts = new PointF[4];
dsts[0] = new PointF(int.Parse(bacakoord["x1proj"].ToString()), int.Parse(bacakoord["y1proj"].ToString()));
dsts[1] = new PointF(int.Parse(bacakoord["x2proj"].ToString()), int.Parse(bacakoord["y2proj"].ToString()));
dsts[2] = new PointF(int.Parse(bacakoord["x3proj"].ToString()), int.Parse(bacakoord["y3proj"].ToString()));
dsts[3] = new PointF(int.Parse(bacakoord["x4proj"].ToString()), int.Parse(bacakoord["y4proj"].ToString()));
HomographyMatrix mywarpmat = CameraCalibration.GetPerspectiveTransform(srcs, dsts);
Image<Bgr, Byte> newImage = sourceImage.WarpPerspective(mywarpmat, 355, 288, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR, Emgu.CV.CvEnum.WARP.CV_WARP_FILL_OUTLIERS, new Bgr(0, 0, 0));
Image<Gray, Byte> newImageGray = newImage.Convert<Gray, Byte>();
Image<Bgr, Byte> imageToShow = newImage.Copy();
Image<Bgr, Byte> imageToShowGaris = newImage.Copy();
ProjectionBox.Image = newImage.Bitmap;
#endregion
}
}
Hi I am getting this error while saving an Image at the given path
string WriteImage(string data, string imgPath)
{
try
{
data = "*" + data + "*";
Bitmap barcode = new Bitmap(1, 1);
Font threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
Graphics graphics = Graphics.FromImage(barcode);
SizeF dataSize = graphics.MeasureString(data, threeOfNine);
barcode = new Bitmap(barcode, dataSize.ToSize());
graphics = Graphics.FromImage(barcode);
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(data, threeOfNine, new SolidBrush(Color.Black), 0, 0);
graphics.Flush();
threeOfNine.Dispose();
graphics.Dispose();
barcode.SetResolution(300, 300);
barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return imgPath.Substring(imgPath.LastIndexOf("\\")+1);
}
catch
{
return "";
}
}
Dont know what i am doing wrong.
As I wrote in my comment, I'm not seeing any problem. The following version of your code outputs information in the event of an error so you can debug it. It also disposes of resources properly:
public static string WriteImage(string data, string imgPath)
{
try
{
data = "*" + data + "*";
using (var dummyBitmap = new Bitmap(1, 1))
using (var threeOfNine = new Font("IDAutomationHC39M", 60, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point))
{
SizeF dataSize;
using (var graphics = Graphics.FromImage(dummyBitmap))
{
dataSize = graphics.MeasureString(data, threeOfNine);
}
using (var barcode = new Bitmap(dummyBitmap, dataSize.ToSize()))
using (var graphics = Graphics.FromImage(barcode))
using (var brush = new SolidBrush(Color.Black))
{
graphics.Clear(Color.White);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
graphics.DrawString(data, threeOfNine, brush, 0, 0);
graphics.Flush();
barcode.SetResolution(300, 300);
barcode.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return imgPath.Substring(imgPath.LastIndexOf("\\") + 1);
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error saving string \"" + data + "\" to a bitmap at location: " + imgPath);
Debug.WriteLine(ex.ToString());
return "";
}
}
I need to loop through a folder and get all of the images and load them into a SQL Server database; as is; meaning whatever format the image is in.
In my code I have to specify the image name which is a problem, especially because I do not know the name of the images in advance. I also attempted looping through the directory via a forloop but that did not work.
Here is the complete code:
class Program
{
string imageFileLocation = #"C:\dev\dbimage\";
string imageFilePrefix = "test";
string imageFileType = ".png";
int numberImageFiles = 1;
int maxImageSize = 10000;
SqlConnection conn = null;
SqlCommand cmd = null;
private void LoadImages()
{
try
{
conn = new SqlConnection(#"MyConnectionStuff");
conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
PrepareInsertImages();
for (int i = 1; i <= numberImageFiles; i++)
{
ExecuteInsertImages(i);
}
}
catch (SqlException ex)
{
Console.Write(ex.Message);
}
finally
{
conn.Close();
}
}
private void ExecuteCommand(string cmdText)
{
int cmdResult;
cmd.CommandText = cmdText;
cmdResult = cmd.ExecuteNonQuery();
}
private void PrepareInsertImages()
{
cmd.CommandText = #"insert into ImageTable
values (#ImageFile, #ImageData)";
cmd.Parameters.Add("#imagefile", SqlDbType.NVarChar, 20);
cmd.Parameters.Add("#imagedata", SqlDbType.Image, 1000000);
cmd.Prepare();
}
private void ExecuteInsertImages(int imageFileNumber)
{
string imageFileName = null;
byte[] imageImageData = null;
imageFileName = imageFilePrefix + imageFileNumber.ToString()
+ imageFileType;
imageImageData = LoadImageFile(imageFileName, imageFileLocation,
maxImageSize);
cmd.Parameters["#ImageFile"].Value = imageFileName;
cmd.Parameters["#ImageData"].Value = imageImageData;
ExecuteCommand(cmd.CommandText);
}
private byte[] LoadImageFile(string fileName, string fileLocation,
int maxImageSize)
{
byte[] imagebytes = null;
string fullpath = fileLocation + fileName;
FileStream fs = new FileStream(fullpath, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(maxImageSize);
return imagebytes;
}
static void Main(string[] args)
{
Program program = new Program();
program.LoadImages();
Console.ReadKey();
}
}
You can enumerate the .png file in a folder like this:
foreach(string filePath in Directory.EnumerateFiles(#"C:\dev\dbimage", "*.png"))
{
}
filePath will contain the full path to the file. If you just want to grab the file name without the full path do:
string fileName = Path.GetFileName(filePath);
Both classes Directory and Path are in the System.IO namespace.