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();
}
}
}
Related
Document is printed from MVC controller to Debian Squeeze Linux server printer using code below in Mono.
Page in printer is A4.
Printed text in paper is too big and unsharp. Rightmost part of text is not visible since it does not fit to page.
If printed from Windows from .NET to HP Laserjet, output is correct.
So it looks like Mono or Samsung ML-331x Series printer zooms bitmap for unknown reason which causes too big and unsharp output.
How to fix this so that bitmap is printed like in windows ?
Possible solutions:
Best way would be to print formatted html directly. How to do it in server where there are no browser installed? wkhtmltopdf does not support printing. I posted it in How to print formatted html in Linux server
Maybe it is possible to use wkhtmltopdf convert html to pdf instead of bitmap I posted it as separate question in How to print pdf in debian linux from MVC controller
wkhtmltoimage can produce also other image formats. Maybe some other format is better ?
Maybe some wkhtmltoimage command line swithches like --width=750 or --dpi can fix this ?
public class Test: Controller
{
public ActionResult Print()
{
PrintOrderVormiga();
return new ContentResult() { Content = "OK" };
}
void PrintOrderVormiga()
{
StringBuilder sb = new StringBuilder();
sb.Insert(0, " test ", 500);
var bmp = ConvertHtmlToBMP("<html><body>" +sb.Tostring()+ "</body></html>");
var doc = new PrintDocument();
doc.PrinterSettings.PrinterName = "Samsung ML-331x Series";
doc.PrintPage += new PrintPageEventHandler(ProvideContent);
pageHeight = doc.DefaultPageSettings.PaperSize.Height;
using (bm = new Bitmap(new MemoryStream(bmp)))
{
lehti = (int)Math.Ceiling(bm.Height / (double)pageHeight);
doc.PrinterSettings.FromPage = 1;
doc.PrinterSettings.ToPage = lehti;
pageno = 0;
doc.Print();
}
}
int pageno, lehti;
int pageHeight;
Bitmap bm;
void ProvideContent(object sender, PrintPageEventArgs e)
{
Rectangle cropRect = new Rectangle(0, pageHeight * pageno++,
bm.Width, pageHeight);
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
e.Graphics.DrawImage(bm, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
e.HasMorePages = pageno < lehti;
}
static byte[] ConvertHtmlToBMP(string html)
{
string programm = "wkhtmltoimage";
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
programm = "wkhtmltoimage-amd64";
}
var p = new Process
{
StartInfo =
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
FileName = Environment.OSVersion.Platform == PlatformID.Win32NT ?
"C:\\Program Files\\wkhtmltopdf\\bin\\" + programm + ".exe" : "/usr/bin/" + programm
}
};
p.StartInfo.Arguments = "--format bmp --disable-javascript --quality 10";
p.StartInfo.Arguments += " - -";
p.Start();
using (var stream = p.StandardInput)
{
byte[] ibuffer = System.Text.Encoding.UTF8.GetBytes(html);
stream.BaseStream.Write(ibuffer, 0, ibuffer.Length);
stream.WriteLine();
}
var buffer = new byte[32768];
byte[] file;
using (var ms = new MemoryStream())
{
while (true)
{
var read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
break;
}
ms.Write(buffer, 0, read);
}
file = ms.ToArray();
}
p.WaitForExit(60000);
var returnCode = p.ExitCode;
p.Close();
return file;
}
}
You can use this HTML to PDF Converter for Mono solution from EvoPdf. The C# code for converting a HTML to PDF in Mono is:
// create the HTML to PDF converter object
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIPAddress, serverPortNumber);
// set service password if necessary
if (serverPassword.Length > 0)
htmlToPdfConverter.ServicePassword = serverPassword;
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
// convert the HTML page from given URL to PDF in a buffer
byte[] pdfBytes = htmlToPdfConverter.ConvertUrl(urlToConvert);
I want you to know the methods to get the image from array of bytes :
I'am using this code but it's throw an exception ,if the size is more than 100 or the length of the arary,and if it's less than 50 it save a messay image
Bitmap b = new Bitmap(#"C:/difflena.jpg");
byte[] pixels = lolo(b);
MemoryStream stream = new MemoryStream(pixels, 0, pixels.Length);
Bitmap bitmap = new Bitmap(stream);
Image<Gray, byte> image = new Image<Gray, byte>(60, 60);
image.Bytes = pixels;
image.Save(file + "face" + "t" + ".bmp");
if (image != null) { Label1.Text = "yes";
public byte[] lolo(Bitmap n)
{
/*ImageFormat imageFormat = n.RawFormat;
byte[] Ret=null;
try
{
using (MemoryStream ms = new MemoryStream())
{
n.Save(ms, imageFormat);
Ret = ms.ToArray();
}
}
catch (Exception) { Label1.Text = "no"; }
return Ret;}
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.
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)));
}
I have data read from 2d bar code pdf417. It contains an embedded image in the format of (jfif), The image is not at the beginning of the decoded data it has some data fields and the image is somewhere after, the data fields does not seam to have fixed lengths. How can I extract the Image from the decoded data. I used ClearImage Library to decode the barcode and I have it as text and Hex.
Please help. Thank you in advance
I was able to extract the image thanks to many experts in StackOverflow, I have being reviewing their posts. The following code explains how to extract the image from a mixed binary file, the code is not so beautiful but it can do the job. It searches for (JFIF) image header and extracts it into an image file.
public static void ExtractImage(string fname)
{
try
{
FileStream fs = new FileStream(fname, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
//read the first binary
char[] soi="Empty".ToCharArray();
br.BaseStream.Position = 0;
long imgpos = 0;
ushort r = 0;
while ((r = br.ReadUInt16())> 0)
{
Console.WriteLine(r);
if (r == 0xd8ff)
{
Console.WriteLine("Detcted----->");
imgpos = br.BaseStream.Position;
break;
//UInt16 jfif = br.ReadUInt16(); // JFIF marker
//Console.WriteLine("jfif " + jfif);
//if (jfif == 0xe0ff || jfif == 57855)
// Console.WriteLine(" also Detected--->");
}
}
//now copy to stream
FileStream str = new FileStream("bcimage.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(str);
br.BaseStream.Position = imgpos-2;
int l = (int)(fs.Length - imgpos - 2);
bw.Write(br.ReadBytes(l));
fs.Close();
br.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}