【发布时间】:2017-06-05 02:14:36
【问题描述】:
我正在使用来自 MATLAB 的一些 .NET 程序集,它产生一个 System.Drawing.Bitmap 对象。我想得到一个带有像素的 MATLAB 矩阵。你是怎么做到的?
我不想将图像保存到磁盘然后使用imread。
【问题讨论】:
标签: c# .net image matlab system.drawing
我正在使用来自 MATLAB 的一些 .NET 程序集,它产生一个 System.Drawing.Bitmap 对象。我想得到一个带有像素的 MATLAB 矩阵。你是怎么做到的?
我不想将图像保存到磁盘然后使用imread。
【问题讨论】:
标签: c# .net image matlab system.drawing
根据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(..) 但这当然很慢。
使用BitmapData,您可以将位图作为像素数组。
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,但这是为了避免不安全。
使用不安全代码,您可以直接操作像素数据。
【讨论】: