我正在学习Emgu.CV,我已经成功地运行了这个例子,我更喜欢从字节数组中读取图像,而不是直接从文件中读取,而且我更喜欢将结果保存到字节数组中,而不是直接保存到文件中。
任何机构可以帮助?
衷心感谢
var _img = CvInvoke.Imread(_jpg); // HOW TO READ FROM BYTE ARRAY
var _fd = new Emgu.CV.CascadeClassifier(_face_classifier);
var _img_gray = new UMat();
CvInvoke.CvtColor(_img, _img_gray, Emgu.CV.CvEnum.ColorConversion.Bgr2Gray);
foreach (Rectangle _face in _fd.DetectMultiScale(_img_gray, 1.1, 10, new System.Drawing.Size(20,20)))
{
CvInvoke.Rectangle(_img, _face, new Emgu.CV.Structure.MCvScalar(255, 255, 255));
}
_img.Save("result.jpg"); // SAVE TO BYTE ARRAY
我理解你的问题其实有两个方面。将图像转换为... byte[]
,并保存一个 byte[]
到一个文件。我先说说比较简单的和后者。
byte[]
归档using(FileStream fs = new FileStream("OutputFile.dat",FileMode.OpenOrCreate))
{
BinaryWriter bs = new BinaryWriter(fs);
bs.Write(byteBuffer);
}
byte[]
从文件byte[] byteBuffer;
using (FileStream fs = new FileStream("InputFile.dat", FileMode.OpenOrCreate))
{
BinaryReader br = new BinaryReader(fs);
// Where 0xF0000 is calculated as Image Width x Height x Bit Depth
byteBuffer = br.ReadBytes(0xF0000);
}
现在是第二部分;我假设你熟悉像素格式,以及真正的图像结构是怎样的。byte[,,]
(或任何其他深度)被序列化为一个单一维度。byte[]
. 如果没有,请询问。
Image
从 byte[]
在下面的例子中 byte[]
的源头,而不是如上所述的加载。byte[]
是无关紧要的,只要它是已知图像尺寸和深度的正确序列化。
int width = 640; // Image Width
int height = 512; // Image Height
int stride = 640 * 3; // Image Stide - Bytes per Row (3 bytes per pixel)
// Create data for an Image 512x640 RGB - 983,040 Bytes
byte[] sourceImgData = new byte[0xF0000];
// Pin the imgData in memory and create an IntPtr to it's location
GCHandle pinnedArray = GCHandle.Alloc(sourceImgData, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// Create an image from the imgData
Image<Rgb, byte> img = new Image<Rgb, byte>(width, height, stride, pointer);
// Free the memory
pinnedArray.Free();
Image
到 byte[]
// Convert the source Image to Bitmap
Bitmap bitmap = sourceImage.ToBitmap();
// Create a BitmapData object from the resulting Bitmap, locking the backing data in memory
BitmapData bitmapData = bitmap.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
// Create an output byte array
byte[] destImgData = new byte[bitmapData.Stride * bitmap.Height];
// Copy the byte array to the destination imgData
Marshal.Copy(bitmapData.Scan0,
destImgData,
0,
destImgData.Length);
// Free the memory
bitmap.UnlockBits(bitmapData);