使用lockbits方法从C#中的图像中提取颜色。 [英] Extracting color from image in C# using lockbits method.
本文介绍了使用lockbits方法从C#中的图像中提取颜色。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从图像中提取蓝色,我为它编写了代码。我在C#中使用lockbits方法。
24位图像 - BGR
[0] =蓝色
[1] =绿色>
[2] =红色
这是代码 -
I want to extract blue color from image, I wrote code for it. I am using lockbits method in C#.
24 bit image - BGR
[0] = Blue
[1] = Green
[2] = Red
Here is code -
BitmapData bitmapdata = bitmap.LockBits (
new Rectangle(
0,
0,
bitmap.Width,
bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb );
IntPtr ptr = bitmapdata.Scan0;
// declare an array to hold
// the bytes of bitmap
int bytes = Math.Abs ( bitmapdata.Stride ) *
bitmap.Height;
byte [ ] values = new byte [ bytes ];
System.Runtime.InteropServices.Marshal.Copy ( ptr, values, 0, bytes );
for ( int i = 0; ( i < values.Length ); i += 3 )
{
// Comparing blue and green and
// blue and red. if blue is greater
// than both pixel than make it
// more intensive otherwise make white
if ( ( values [ i ] - values [ i + 1 ] > 9 ) &&
( values [ i ] - values [ i + 2 ] > 9 )
{
values [ i ] = 255;
values [ i + 1 ] = 0;
values [ i + 2 ] = 0;
}
else
{
values [ i ] = 255;
values [ i + 1 ] = 255;
values [ i + 2 ] = 255;
}
}
bitmap.Save("bitmap.jpg");
此代码工作正常但在一张图片中我遇到了问题,当图像没有颜色时,它会提取红色而不是蓝色。
运行此代码时,此图像应为白色。
我不想使用getpixel或setpixel方法。
附图像。
This code is working fine but in one image I got problem, it was extracting red color instead of blue when the image has no color.
This image should be white when I run this code.
I don't want to use getpixel or setpixel method.
Image attached.
推荐答案
它只是意味着其中一个图像恰好具有不同的像素格式。不同的格式会产生不同的内存布局。您必须阅读该文件,然后阅读属性PixelFormat
:
https://msdn.microsoft.com/en-us/library/system.drawing.image.pixelformat(v = VS .110).aspx [ ^ ],
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat%28v=vs.110%29.aspx [ ^ ]。
阅读给定像素格式的描述并调整您的假设内存布局。
-SA
It simply means that one of the images happens to have different pixel format. Different formats makes different memory layouts. You have to read the file and then read the propertyPixelFormat
:
https://msdn.microsoft.com/en-us/library/system.drawing.image.pixelformat(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat%28v=vs.110%29.aspx[^].
Read the description on the given pixel format and adjust your assumed memory layout.
—SA
这篇关于使用lockbits方法从C#中的图像中提取颜色。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文