我正在使用MATLAB的一些.NET程序集,它会生成一个System.Drawing.Bitmap
对象。我想得到一个MATLAB矩阵,其中的像素。你是怎样做的?从System.Drawing.Bitmap中提取像素
我不想将图像保存到磁盘,然后使用imread
。
我正在使用MATLAB的一些.NET程序集,它会生成一个System.Drawing.Bitmap
对象。我想得到一个MATLAB矩阵,其中的像素。你是怎样做的?从System.Drawing.Bitmap中提取像素
我不想将图像保存到磁盘,然后使用imread
。
基于Jeroen的答案,这里是MATLAB代码来进行转换:
% make sure the .NET assembly is loaded
NET.addAssembly('System.Drawing');
% read image from file as Bitmap
bmp = System.Drawing.Bitmap(which('football.jpg'));
w = bmp.Width;
h = bmp.Height;
% lock bitmap into memory for reading
bmpData = bmp.LockBits(System.Drawing.Rectangle(0, 0, w, h), ...
System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
% get pointer to pixels, and copy RGB values into an array of bytes
num = abs(bmpData.Stride) * h;
bytes = NET.createArray('System.Byte', num);
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, bytes, 0, num);
% unlock bitmap
bmp.UnlockBits(bmpData);
% cleanup
clear bmp bmpData num
% convert to MATLAB image
bytes = uint8(bytes);
img = permute(flipdim(reshape(reshape(bytes,3,w*h)',[w,h,3]),3),[2 1 3]);
% show result
imshow(img)
最后一句是很难理解的。它实际上等同于以下:
% bitmap RGB values are interleaved: b1,g1,r1,b2,g2,r2,...
% and stored in a row-major order
b = reshape(bytes(1:3:end), [w,h])';
g = reshape(bytes(2:3:end), [w,h])';
r = reshape(bytes(3:3:end), [w,h])';
img = cat(3, r,g,b);
结果:
如果你想修改个别像素,你可以调用Bitmap.SetPixel(..),但这是缓慢的课程。
随着位图数据你可以得到像素数组的位图。
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
// code
// Unlock the bits.
bmp.UnlockBits(bmpData);
见: http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx
在他们使用Marshal.Copy的例子,但这是,如果你想避免不安全。
随着不安全代码,你可以直接操纵像素数据。
... bobpowell ..链接无法访问。 – antonio
谢谢@Amro!那工作很好。 –