2013-09-10 43 views

回答

3

基于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); 

结果:

image

+0

谢谢@Amro!那工作很好。 –

2

如果你想修改个别像素,你可以调用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的例子,但这是,如果你想避免不安全

随着不安全代码,你可以直接操纵像素数据。

+0

... bobpowell ..链接无法访问。 – antonio