JavaCV FaceRecognizer predict not working - opencv

I'm using opencv 2.4.6 and javacv 0.6. I'm trying to make face recognizer.
This is my code:
FaceRecognizer ef = createEigenFaceRecognizer(1, 0.00000001);
int facewidth = 92, faceheight = 112;
private boolean stopRec = false;
List<String> names = new ArrayList<String>();
public void recognize(IplImage face) {
int predicted;
int [] tabPredicted = new int[2];
double[] predConfTab = new double[2];
IplImage resizedFace = IplImage.create(new CvSize(facewidth, faceheight), IPL_DEPTH_8U, 1);
cvResize(face, resizedFace);
if (names.size() != 0)
{
ef.predict(resizedFace, tabPredicted, predConfTab);
predicted = tabPredicted[0];
}
else
{
predicted = -1;
}
if(predicted == -1 )
{
//adding user like:
int i = names.size();
names.add(name);
System.out.println("Identified new person: " + names.get(i));
MatVector mv = new MatVector(1);
mv.put(0, resizedFace);
int[] u = new int[] {i};
ef.train(mv, u);
}
I tried lot of configurations. I'm sure that i have valid face image in grayscale. The problem is that after ef.predict(resizedFace, tabPredicted, predConfTab);
tabPredicted[0] is always index of last added user and predConfTab[0] always equals 0, so it means that any faces exacly matches the last one added.

Related

how to display first two objects in loop of anchor in sceneform ARcCore

if (frame.getCamera().getTrackingState() == TrackingState.TRACKING && anchorsts && !placed) {
Session session = arFragment.getArSceneView().getSession();
String type = "fwd";
int distance = 0;
int nextPoint = 1;
String[] positions = {"u", "u","r", "r","r", "r", "r", "r", "r", "r"};
if (turnStatus == null){
turnStatus = positions[distance];
Log.i("turnStatus", "pos " + positions[distance]);
}
float[] rotation = {0, 0, 0, 0};
do {
if (positions[distance].equals("u")) {
turnStatus = "u";
placeNav(session, new float[]{dx, dy, dz}, rotation, positions[distance]);
if (!turnStatus.equals(positions[nextPoint])) {
if (positions[nextPoint].equals("r")) {
turnDistance = distance;
}
}
} else if (positions[distance].equals("r")){
turnDistance ++;
turnStatus = "r";
placeNav(session, new float[]{turnDistance, -1.5f, -turnDistance}, rotation, positions[distance]);
if (!turnStatus.equals(positions[nextPoint])) {
if (positions[nextPoint].equals("u")) {
}
}
}
distance++;
nextPoint ++;
} while (distance <9);
placed = true; //to place the arrow just once.
}
private void placeNav(Session session, float[] pos, float[] rotation, String type) {
AnchorNode anchorNode = new AnchorNode(anchor);
currentAnchorNode = anchorNode;
anchorNode.setParent(arFragment.getArSceneView().getScene());
Node arrow = new Node();
arrow.setParent(anchorNode);
if (type.equals("u"))
arrow.setRenderable(andyRenderable);
else if (type.equals("r"))
arrow.setRenderable(andyRenderable);
}
the above code is used to render a loop of renderables into scene. I need to display only first two renderables and display next renderables while user is moving forward. here the positions array isnused to render objects into scene. Please to help me to implement this
Just create the first two renderable in onCreate method. For creating the other renderable, when the person is moving forward, you should check if the new position of the camera is in front of the previous position of the camera.
Vector3 newCameraPosition = getScene().getCamera().getWorldPosition();
Vector3 direction = Vector3.subtract(newCameraPosition, oldCameraPosition);
Quaternion lookRotation = Quaternion.lookRotation(direction, Vector3.up());
double product =
(newCameraPosition.x - oldCameraPosition.x) * direction.x + (newCameraPosition.y - oldCameraPosition.y) * direction.y + (newCameraPosition.z - oldCameraPosition.z) * direction.z;
if (product > 0.0) {
// means camera moved forward
}

I can't find why memory isn't release using in SharpDX

I'm making on some Winform application, I noticed my program's memory issue.
This is my winform custom control code.
using System;
using System.Drawing;
using System.Windows.Forms;
using DX = SharpDX;
using D2D = SharpDX.Direct2D1;
using SharpDX.Mathematics.Interop;
using DW = SharpDX.DirectWrite;
namespace WinFormTest
{
public partial class BitmapSurface : Control
{
D2D.Factory d2dFactory;
DW.Factory dwFactory;
D2D.WindowRenderTarget wrt;
D2D.BitmapRenderTarget brt;
Rectangle clippingRect = new Rectangle(0, 0, 100, 100);
public BitmapSurface()
{
InitializeComponent();
InitializeRenderer();
}
DX.Size2 clientSize2;
DX.Size2F clientSize2f;
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (clientSize2 == null)
clientSize2 = new DX.Size2();
if (clientSize2f == null)
clientSize2f = new DX.Size2F();
clientSize2.Width = ClientSize.Width;
clientSize2.Height = ClientSize.Height;
clientSize2f.Width = ClientSize.Width;
clientSize2f.Height = ClientSize.Height;
if (wrt != null)
{
wrt.Resize(clientSize2);
}
if (brt != null)
{
brt.Dispose();
brt = new D2D.BitmapRenderTarget(wrt, D2D.CompatibleRenderTargetOptions.None, clientSize2f, null, null);
brt.AntialiasMode = D2D.AntialiasMode.Aliased;
}
this.Invalidate();
}
private D2D.SolidColorBrush GetBrush(float r, float g, float b, float a = 255)
{
var brush = new D2D.SolidColorBrush(
wrt, new RawColor4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f));
return brush;
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
clippingRect = this.ClientRectangle;
var rect = clippingRect;
DrawBitmap();
}
public void InitializeRenderer()
{
int width = this.ClientSize.Width;
int height = this.ClientSize.Height;
D2D.HwndRenderTargetProperties hrtp = new D2D.HwndRenderTargetProperties();
hrtp.Hwnd = this.Handle;
hrtp.PixelSize = new DX.Size2(width, height);
// D2DFactory
if (d2dFactory == null)
d2dFactory = new D2D.Factory();
// DirectWrite
if (dwFactory == null)
dwFactory = new DW.Factory();
wrt = new D2D.WindowRenderTarget(d2dFactory, new D2D.RenderTargetProperties(), hrtp);
wrt.AntialiasMode = D2D.AntialiasMode.Aliased;
brt = new D2D.BitmapRenderTarget(wrt, D2D.CompatibleRenderTargetOptions.None, new DX.Size2F(width, height), null, null);
brt.AntialiasMode = D2D.AntialiasMode.Aliased;
}
public void DrawBitmap()
{
brt.BeginDraw();
brt.Clear(new RawColor4(0, 0, 0, 1));
// Draw Something
for (int i = 0; i < 1000; i++)
{
brt.DrawLine(
new RawVector2(0, i),
new RawVector2(90, 90 + i),
GetBrush(255, 255, 255));
}
for (int i = 0; i < 1000; i++)
{
brt.FillRectangle(
new RawRectangleF(90, 0 + i, 150, 10 + i),
GetBrush(255 - i, 255 - i, 255 - i));
}
brt.EndDraw();
wrt.BeginDraw();
wrt.DrawBitmap(brt.Bitmap, 1, D2D.BitmapInterpolationMode.NearestNeighbor);
wrt.EndDraw();
}
}
}
My program's mainform can have many childs, Child draw somethings with SharpDX.
Memory usage is increase When I open child forms, but after closing child form and GC.Collect memory usage is NOT decrease.
Is this bad usage for SharpDX?

Multiple Bills Printing in C#

I am developing a module in a billing system for a national Utility. The module is supposed to pick all successfully billed customers and print their bills.Bills are written as text files and saved on a local folder and the program has to pick them up and print them one by one.I'm using a DFX-9000 printer and pre-formatted roll paper,however,each time a new bill comes in,the printer skips some space before it prints it which distorts the 2nd and following bills.
I tried putting all the bills in a single text file which prints well when opened in notepad but not in my code.
Here is part of my code
Font printFont = new Font("Lucida Console", 10);
//static string filename;
StreamReader reader = new StreamReader(Filename);
public void Print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("myPaper", 826, 1169);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
//pd.DefaultPageSettings.PrinterSettings.IsPlotter = true;
pd.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.Custom;
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
pd.Print();
if (reader != null)
reader.Close();
Console.WriteLine("Printout Complete");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs pe)
{
StringFormat sf = new StringFormat();
Graphics g = pe.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 40;//pe.MarginBounds.Left;
float topMargin = pe.MarginBounds.Top;
string line = null;
linesPerPage = 500;// pe.MarginBounds.Height / printFont.GetHeight(g);
while (count <= linesPerPage &&((line = reader.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
count++;
}
if (line != null)
{
pe.HasMorePages = true;
}
else
{
pe.HasMorePages = false;
}
Could your printing.papersize be wrong? I notice it's 1169, doesn't standard paper stop at 1100?

Image Stitching using EMGU CV

I would like to do image stitching to produce a panoramic view image at one position roughly 360 degrees. For now my coding is like this...
this is the capture while stitching button coding
int n = 1;
String fileName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.0.4/view/snapshot.shtml?picturepath=/jpg/image.jpg");
res = request.GetResponse();//.GetResponse();
string[] CapturedImage = new string[28];
Image<Bgr, Byte>[] TotalImage = new Image<Bgr, Byte>[28];
do
{
fileName = #"D:\Ervin Loong (116834P)\Program Testing\Images\" + "Image" + (n++) + ".jpg"; // File location & Filename.
}
while (System.IO.File.Exists(fileName)); // check for existing previously saved files. If yes, add another new picture.
{
AMCLiveFeed.SaveCurrentImage(0, fileName);
res.Close();
}
if (n == 29)
{
for (int i = 0; i < 28; i++) // i < 10 - save 10 images
{
CapturedImage[i] = #"D:\Ervin Loong (116834P)\Program Testing\Images\" + "Image" + (i + 1) + ".jpg";
TotalImage[i] = new Image<Bgr, byte>(CapturedImage[i]);
}
try
{
using (Stitcher stitcher = new Stitcher(false)) //Although the Stitcher class is built for GPU acceleration, a false flag must be passed to enable CPU processing. As GPU is not implemented yet.
{
Image<Bgr, Byte> CapturedResult = stitcher.Stitch(TotalImage);
IMGBXDisplayStitched.Image = CapturedResult; //imagebox displays stitched results.
}
}
finally
{
foreach (Image<Bgr, Byte> DisposeImage in TotalImage)
{
DisposeImage.Dispose();
}
}
}

POST image from webcam in Silverlight window to MVC Controller

I have an MVC 4 application with a button for taking a photo that opens up a new window with javascript which contains a silverlight application in it. The silverlight application can then take a photo using the webcam and store it as a Writeable Bitmap. What I would like to do is then push that bitmap onto an action in my controller for saving to the database and refreshing the view.
I know I need to send the image as a post to my controller, but any code examples or suggestions on how I would go about doing that would be greatly appreciated. I think it should work as follows, Button Click for saving the image in my silverlight application would call a POST to the MVC controller and attach the image stream as a parameter in the controller, and the controller can then take the stream and push it up to the database then I can close the silverlight window. Just not sure how to go about coding that.
You could send the image using a WebClient. Let's suppose that you have the image inside your Silverlight application in a byte array:
byte[] image = ... get the image from your webcam
var client = new WebClient();
var uri = new Uri("http://example.com/photos/upload");
client.OpenWriteCompleted += (sender, e) =>
{
var buffer = (byte[])e.UserState;
e.Result.Write(buffer, 0, buffer.Length);
e.Result.Close();
};
client.OpenWriteAsync(uri, "POST", image);
and on the MVC side:
[HttpPost]
public ActionResult Upload()
{
byte[] image = new byte[Request.InputStream.Length];
Request.InputStream.Read(image, 0, image.Length);
// TODO: do something with the uploaded image here ...
}
Thank you for the reply. This is exactly what I was looking for, however ive run into a problem. Silverlight gives me the webcam snapshot as a WriteableBitmap type. Which I then tried to convert to a byte[] array before sending it over to MVC. It is saving to the database successfully, however it does not appear to be a valid image when I try to pull it back out from the database and display it. Is there an issue that you can see with my conversion code? Or perhaps can I send it over as an image type, or can I only send over byte[] arrays through http posts like this?
In my Silverlight application:
private void SendImage()
{
var client = new WebClient();
var uri = new Uri("http://localhost:4600/GuestBadge/GetCameraImage");
client.OpenWriteCompleted += (sender, e) =>
{
var buffer = (byte[])e.UserState;
e.Result.Write(buffer, 0, buffer.Length);
e.Result.Close();
};
client.OpenWriteAsync(uri, "POST", ToByteArray(SnapShot));
}
public static byte[] ToByteArray(WriteableBitmap bmp)
{
// Init buffer
int w = bmp.PixelWidth;
int h = bmp.PixelHeight;
int[] p = bmp.Pixels;
int len = p.Length;
byte[] result = new byte[4 * w * h];
// Copy pixels to buffer
for (int i = 0, j = 0; i < len; i++, j += 4)
{
int color = p[i];
result[j + 0] = (byte)(color >> 24); // A
result[j + 1] = (byte)(color >> 16); // R
result[j + 2] = (byte)(color >> 8); // G
result[j + 3] = (byte)(color); // B
}
return result;
}
And in my controller:
[HttpPost]
public ActionResult GetCameraImage()
{
byte[] image = new byte[Request.InputStream.Length];
Request.InputStream.Read(image, 0, image.Length);
var getPerson = (from a in db.Persons where a.PersonID == 3 select a).FirstOrDefault();
getPerson.Picture = image;
db.SaveChanges();
return null;
}
I ended up using FJCore http://code.google.com/p/fjcore/ to encode my WriteableBitmap into JPEG and then converted that to BASE64 using code I found at this question Using FJCore to encode Silverlight WriteableBitmap THANKS!. Then in turn converted that out to a byte[] array and sent it to MVC using your code and now its working great. I'm pretty new at all this stuff and didn't quite understand the encoding process enough before. Below is the code I used for this. Thanks again for your help!
private static string GetBase64Jpg(WriteableBitmap bitmap)
{
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int bands = 3;
byte[][,] raster = new byte[bands][,];
for (int i = 0; i < bands; i++)
{
raster[i] = new byte[width, height];
}
for (int row = 0; row < height; row++)
{
for (int column = 0; column < width; column++)
{
int pixel = bitmap.Pixels[width * row + column];
raster[0][column, row] = (byte)(pixel >> 16);
raster[1][column, row] = (byte)(pixel >> 8);
raster[2][column, row] = (byte)pixel;
}
}
ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };
FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
MemoryStream stream = new MemoryStream();
JpegEncoder encoder = new JpegEncoder(img, 90, stream);
encoder.Encode();
stream.Seek(0, SeekOrigin.Begin);
byte[] binaryData = new Byte[stream.Length];
long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
string base64String =
System.Convert.ToBase64String(binaryData,
0,
binaryData.Length);
return base64String;
}
private void SendImage()
{
var client = new WebClient();
var uri = new Uri("http://localhost:4600/GuestBadge/GetCameraImage");
client.OpenWriteCompleted += (sender, e) =>
{
var buffer = (byte[])e.UserState;
e.Result.Write(buffer, 0, buffer.Length);
e.Result.Close();
};
client.OpenWriteAsync(uri, "POST", Convert.FromBase64String(GetBase64Jpg(SnapShot)));
}

Resources