TakePictureForm.cs
13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using ImageFilters;
using MoyaSignup.Dataclasses;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MoyaSignup
{
public partial class TakePictureForm : Form
{
Pen RetanglePen = new Pen(Color.Blue);
int RetangleHeight = 424;
int RetangleWidth = 310;
int DefaultCropWidth = 263;
int DefaultCropHeight = 360;
int camHeight = 720;
//bool freeze;
// bool pictureTaken = false;
//bool cameraOpen = false;
//private CameraFrameSource _frameSource;
private static Bitmap latestFrame;
public event EventHandler Changed;
public bool PictureTaken = false;
Image<Bgr, Byte> currentFrame;
Image<Bgr, Byte> currentFullFrame;
HaarCascade face;
Image<Gray, byte> gray = null;
Rectangle cropRectangle = new Rectangle();
List<Capture> webCams;
int pictureCountDown = 3;
Dictionary<decimal, Capture> camScores = new Dictionary<decimal, Capture>();
public TakePictureForm()
{
InitializeComponent();
}
Capture selectedCam = null;
private void TakePictureForm_Load(object sender, EventArgs e)
{
startCapturing();
cropRectangle.X = 189;
cropRectangle.Y = 0;
cropRectangle.Width = DefaultCropWidth;
cropRectangle.Height = DefaultCropHeight;
}
private void startCapturing()
{
if (!DesignMode)
{
Debug.WriteLine("[takepictureform] Starting capture for cameras");
webCams = new List<Emgu.CV.Capture>();
try
{
face = new HaarCascade("haarcascade_frontalface_default.xml");
}
catch (Exception ex)
{
pictureBox.Text = "Select A Camera";
MessageBox.Show(ex.Message);
Debug.WriteLine("[takepictureform] Failed to initialize camera settings");
return;
}
if (Program.CaptureDevices != null)
{
foreach (DsDeviceContainer device in Program.CaptureDevices)
{
try
{
Capture capture = new Capture(device.Idx);
capture.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 720);
capture.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 1280);
capture.QueryFrame();
Debug.WriteLine("[takepictureform] adding webcam " + device.Device.Name + "' to webcams");
webCams.Add(capture);
}
catch (Exception ex)
{
Debug.WriteLine("[takepictureform] Could not start capturing for device '" + device.Device.Name + "'. Error: " + ex.Message);
continue;
}
}
Program.WebCams = webCams;
captureTimer.Enabled = true;
captureTimer.Start();
selectCamTimer.Enabled = true;
selectCamTimer.Start();
}
else
{
Debug.WriteLine("[takepictureform] Failed to start capturing because videoCaptureDevices was null");
}
}
}
private void takePictureTimer_Tick(object sender, EventArgs e)
{
if (pictureCountDown == 0)
{
takePictureTimer.Enabled = false;
takePictureTimer.Stop();
captureTimer.Enabled = false;
captureTimer.Stop();
Debug.WriteLine("[takepictureform] Kuva otettu");
pictureCountDown = 3;
secondsLabel.Visible = false;
//pictureTakenLabel.Text = "Kuva otettu";
btnTakePic.Enabled = false;
//cameraOpen = false;
btnTakePic.Text = "Ota kuva";
pictureTakenLabel.Visible = false;
pictureTakenLabel.Text = "Kuva otetaan automaattisesti";
//thrashOldCamera();
//pbIncoming.Image = latestFrame;
if (Program.Form1 != null)
Program.Form1.SetUsersPicture(latestFrame);
btnTakePic.Enabled = true;
PictureTaken = true;
foreach (Capture cam in webCams)
{
cam.Dispose();
}
if (Changed != null)
Changed(null, null);
this.Visible = false;
this.SendToBack();
}
else
{
Debug.WriteLine("[takepictureform] Kuvanottolaskuri käynnissä, " + pictureCountDown.ToString() + "s jäljellä.");
pictureCountDown -= 1;
secondsLabel.Text = pictureCountDown.ToString() + "s päästä";
}
}
private void captureTimer_Tick(object sender, EventArgs e)
{
FrameGrabber(captureTimer, null);
}
private void FrameGrabber(object sender, EventArgs e)
{
//Debug.WriteLine("[takepictureform] Trying to find a face in the frames from the webcams");
Dictionary<Image<Bgr, byte>, decimal> croppedImages = new Dictionary<Image<Bgr, byte>, decimal>();
Dictionary<Image<Bgr, byte>, Rectangle> cropRectangles = new Dictionary<Image<Bgr, byte>, Rectangle>();
List<Image<Bgr, byte>> fullFrames = new List<Image<Bgr, byte>>();
lock(camScores)
{
camScores = new Dictionary<decimal, Capture>();
}
for (int i = 0; i < webCams.Count; i++)
{
decimal score = 0;
Capture grabber = webCams[i];
try
{
currentFullFrame = grabber.QueryFrame();
currentFrame = currentFullFrame.Resize(640, 360, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC); //640x360
}catch(Exception ex)
{
Debug.WriteLine("[takepictureform] Could not get frame from camera. Ex: " + ex.Message);
return;
}
gray = currentFrame.Convert<Gray, Byte>();
MCvAvgComp[][] facesDetected = null;
if (gray != null)
{
//Face Detector
facesDetected = gray.DetectHaarCascade(
face,
1.1,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(50, 50));
}
//Action for each element detected
if (facesDetected != null && facesDetected[0].Length > 0)
{
MCvAvgComp f = facesDetected[0][0];
//decimal width = ((decimal)f.rect.Width) * 3.1M;
decimal width = ((decimal)f.rect.Width) * 2.8M;
decimal height = width * 1.36774193548M;
int x = (f.rect.X + f.rect.Width / 2) * 2;
x = (int)(x - width / 2);
int y = (f.rect.Y + f.rect.Height / 2) * 2;
y = (int)(y - height / 2);
int x1 = (int)(x + width / 2);
if (x1 >= 1280)
x1 = 1279;
int y1 = (int)(y + height / 2);
if (y1 >= 720)
y1 = 719;
decimal distance = (decimal)Math.Sqrt(Math.Pow((double)(x1 - 640), 2) + Math.Pow((double)(y1 - 360), 2));
score += distance;
// allow offset
if (y < 0 && y > -50)
y = 0;
if (y + height > camHeight && y + height < camHeight + 150)
y = camHeight - (int)height - 1;
if (x + width <= 1280 && y + height <= camHeight && x >= 0 && y >= 0)
{
Rectangle cropRect = new Rectangle(x, y, (int)width, (int)height);
Image<Bgr, byte> croppedImage = currentFullFrame.Copy(cropRect);
croppedImage = croppedImage.Resize(310, 424, INTER.CV_INTER_CUBIC);
//Debug.WriteLine("[takepictureform] Adding score '" + score + "' to croppedImageDictionary.");
croppedImages.Add(croppedImage, score);
cropRectangles.Add(croppedImage, cropRect);
lock (camScores)
{
camScores.Add(score, webCams[i]);
}
currentFullFrame.Draw(cropRect, new Bgr(Color.Green), 2);
fullFrames.Add(currentFullFrame.Resize(640, 360, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC));
}
}
}
decimal bestScore = 300;
Image<Bgr, byte> bestImage = null;
int bestImageIdx = 0;
int j = 0;
foreach (Image<Bgr, byte> image in croppedImages.Keys)
{
if (croppedImages[image] < bestScore)
{
if (selectedCam != null)
{
lock (camScores)
{
if (camScores[croppedImages[image]] == selectedCam)
{
bestImage = image;
bestImageIdx = j;
bestScore = croppedImages[image];
break;
}
}
}
else
{
bestImage = image;
bestImageIdx = j;
bestScore = croppedImages[image];
}
}
j++;
}
if (bestImage != null)
{
//Debug.WriteLine("[takepictureform] Found best image from web cam captures.");
if(selectedCam == null)
{
decimal score = croppedImages[bestImage];
lock(camScores)
{
selectedCam = camScores[score];
}
}
Rectangle rect = cropRectangles[bestImage];
int x = (int) rect.X / 2;
int y = (int)rect.Y / 2;
int width = (int)rect.Width / 2;
int height = (int)rect.Height / 2;
cropRectangle = new Rectangle( x, y, width, height);
latestFrame = BitmapFilter.Crop(bestImage.Bitmap, RetangleWidth, RetangleHeight, ImageFilters.BitmapFilter.AnchorPosition.Free);
if (fullFrames.Count > bestImageIdx)
pictureBox.Image = fullFrames[bestImageIdx].Bitmap;
//pbIncoming.Image = latestFrame;
}
else
{
//Debug.WriteLine("[takepictureform] Could not find best picture from web cam feeds");
Image<Bgr, byte> fullFrame = null;
if (selectedCam != null)
fullFrame = selectedCam.QueryFrame().Resize(640, 360, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
else
fullFrame = webCams[0].QueryFrame().Resize(640, 360, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
latestFrame = BitmapFilter.Crop(fullFrame.Bitmap, cropRectangle.Width, cropRectangle.Height, ImageFilters.BitmapFilter.AnchorPosition.Free);
//int x = (640 - DefaultCropWidth) / 2;
//int y = (360 - DefaultCropHeight) / 2;
//cropRectangle = new Rectangle(x, y, DefaultCropWidth, DefaultCropHeight);
fullFrame.Draw(cropRectangle, new Bgr(Color.Red), 2);
//pbIncoming.Image = latestFrame;
pictureBox.Image = fullFrame.Bitmap;
}
}
private void btnTakePic_Click(object sender, EventArgs e)
{
takePictureTimer.Enabled = true;
takePictureTimer.Start();
pictureTakenLabel.Visible = true;
secondsLabel.Visible = true;
}
private void selectCamTimer_Tick(object sender, EventArgs e)
{
lock (camScores)
{
if (camScores != null && camScores.Keys.Count > 0)
{
decimal score = camScores.Keys.Min();
selectedCam = camScores[score];
}
}
}
}
}