这使我困惑了两个小时。读取图像文件会导致Matlab中的imread与C#中的Image.FromFile之间的像素值不同?为什么图像的像素值在读取方法上有所不同?
aa=imread('myfile.tif')
max(aa(:)) = 248 in matlab
在C#
var image2Array = imageToByteArray((Bitmap) Image.FromFile("myfile.tif"));
byte maxx = 0;
foreach(var a in image2Array)
{
maxx = Math.Max(maxx, a);
}
//maxx = 255
Futhermore,在Matlab,
aa(1,1) = 13,
aa(1,2) = 13
但在C#
image2Array[0]=17,
image2Array[1]=0
他们应该是相同的。
顺便说一下,在这种情况下,像素类型是uint8。所以没有尺寸差异。
如果你问我如何从Image获得字节数组,我使用MSDN document来制作这种方法。
public byte[] imageToByteArray(Bitmap bmp)
{
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(
rect,
ImageLockMode.ReadWrite,
bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride)*bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
return rgbValues;
}
我在这里做错了什么?我怀疑他们使用不同的阅读算法,因为两个结果图像看起来相同。
UPDATE:
我不认为有什么不对我在做什么。我的结论是,读取tif作为位图是问题的原因。确认这个理论,
我显示了两个图像,他们看起来完全一样。所以我认为我没有犯错。
我试着用opencv读取同一个文件,其像素值与matlab中的完全一样。这对我来说令人惊讶。我从现在开始非常谨慎地在C#中使用Bitmap。
是的,我正在尝试使用OpenCV。感谢您的确认。 –
我能用matlab复制imread与OpenCV的图像。所以我认为将它作为位图阅读并不是一个好主意,这对我来说是令人惊讶的。 –