I got a problem with Lockbits. I'm searching black pixels, and because it does not seem right, I'm using a WindowPopup to print the colors of every pixel, but it's like my program is using another picture.
alt text http://i208.photobucket.com/albums/bb91/Savaronna/pixel-1.jpg?t=1234874238
I marked the first found black pixel red. As you can see there are several other pixels that should match too. What am I doing wrong?
This is my script, do I oversee something?
Bitmap b = this.TableListBMP;
BitmapData bmpData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format32bppPArgb);
int stride = bmpData.Stride;
IntPtr Scan0 = bmpData.Scan0;
unsafe
{
byte * p = (byte *)(void *)Scan0;
int nOffset = bmpData.Stride - b.Width*4;
int xOffset, yOffset;
for(int y=5; y<b.Height; ++y)
{
for(int x=1; x<b.Width; ++x)
{
MessageBox.Show(
string.Format("x={0}, y={1}, ARGB={2},{3},{4},{5}",
x, y,
Convert.ToString(p[(y*stride)+(x*4)]),
Convert.ToString(p[(y*stride)+(x*4)+1]),
Convert.ToString(p[(y*stride)+(x*4)+2]),
Convert.ToString(p[(y*stride)+(x*4)+3])));
p +=4;
}
// EDIT: This line should be removed
p += nOffset;
}
}
b.UnlockBits(bmpData);
If you are using offsets such as p[((y)*stride)+((x)*4)], you probably shouldn't be increasing p at all? Surely you've already handled that (x and y) with the multiplication? Also, bmpData.Stride - b.Width*4 is not (as far as I can see) a meaningful number... the stride is the rows size including padding.
Either remove the "p += ..." code, or change the offset algorithm. At the moment you are skipping data (bad) and accessing data outside of the object (very bad).
Related
The method for editing Bitmap using BitmapData and Lock and UnlockBits taken from the MSDN seems to work very differently on Bitmaps with with different sizes. It only does this on PixelFormat.Format24bppRgb and changing it seems to fix it, but I'd like to know what's going on.
Here's the method for reference:
private void LockUnlockBitsExample(PaintEventArgs e)
{
// Create a new bitmap.
Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.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);
// Set every third value to 255. A 24bpp bitmap will look red.
for (int counter = 2; counter < rgbValues.Length; counter += 3)
rgbValues[counter] = 255;
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
// Draw the modified image.
e.Graphics.DrawImage(bmp, 0, 150);
}
It works just fine for Bitmap(200, 200) or Bitmap(200,250). But when it's used on Bitmap(50, 50) or most of the other sizes it goes completely crazy...
The rgbValues array has unexpected length of 7600. (The expected length would be Width * Height * Bytes per pixel = 50 * 50 * 3 = 7500)
This causes it to throw IndexOutOfRange Exception in most cases
I tried to change the value added to the counter but none seems to work
for (int counter = 10; counter + 10 < rgbValues.Length; counter += n)
rgbValues[counter] = 255;
//Doesn't work for any number put for n from 2 to 10
//I also limited it from beginning and end just to try
//if it's not changing some crucial value in the bytes
//(I know it's a nonsense but I tried)
If 3 is put for n (referring to the code above) it yields a picture with 1st row red, 2nd blue, 3rd green, repeat
If 1 is put there it actually makes the whole picture white
Can someone please explain why is this happening? And how can this be fixed? (besides changing the format)
Note: I'm not keen on this format but I'd like to know what's actually going on.
**
How to make 'GetPixel2' work for finding the color at a point
**
So I have a bitmap with lots of single colored shapes.
I have a list of x,y points for those shapes. Then, a second list
with the expected color at those points.
Finally have an algorithm using bitmap.Getpixel and SetPixel working.
Which was definitely slow.
http://csharpexamples.com/fast-image-processing-c/
Suggests using direct memory access to solve this. I'd like to use their sample without looping through the entire image, and hit a single x,y point.
Bitmap bmp2 = (Bitmap)Bitmap.FromFile(Environment.CurrentDirectory + #"\Content\map\provinces.bmp");
BitmapData bitmapData = bmp2.LockBits(new System.Drawing.Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadWrite, bmp2.PixelFormat);
int bytesPerPixel = System.Drawing.Bitmap.GetPixelFormatSize(bmp2.PixelFormat) / 8;
int heightInPixels = bitmapData.Height;
int widthInBytes = bitmapData.Width * bytesPerPixel;
System.Drawing.Point pt = new System.Drawing.Point((int)provpos2[0].X, (int)provpos2[0].Y);
System.Drawing.Color targetColor = System.Drawing.Color.FromArgb(255, provcolors[0].R, provcolors[0].G, provcolors[0].B);
if (!ColorMatch(GetPixel2(pt.X, pt.Y, bytesPerPixel, bitmapData), targetColor)){
// This hits the completely wrong area.
}
public System.Drawing.Color GetPixel2(int x, int y, int bytesPerPixel, BitmapData bitmapData)
{
unsafe
{
byte* ptrFirstPixel = (byte*)bitmapData.Scan0;
byte* currentLine = ptrFirstPixel + (y * bitmapData.Stride);
x = x + bytesPerPixel;
System.Drawing.Color a = System.Drawing.Color.FromArgb(255, currentLine[x + 2], currentLine[x + 1], currentLine[x]);
return a;
}
}
public static bool ColorMatch(System.Drawing.Color a,System.Drawing.Color b)
{
return (a.ToArgb() & 0xffffff) == (b.ToArgb() & 0xffffff);
}
bytesPerPixel comes out at 3. Tried changing it to 4 just hits another undesired location on the bitmap.
It seems to hit around 1023x,351y instead of the desired 3084x,319y on a 5632x2048 bitmap.
Not entirely sure why it doesnt workout fo you, but keep in mind this:
Bits per pixel comes from colour format used there are a few formats some are handier then others, and sometimes you need to convert them to a strict RGB format. ea 8 bits per colour channel, there also exists RGBA, and there is RGB in bitwise 565 notation as used in some camera's, and there is 24bits per colour. Some formats are not supported in winforms, but are supported in wpf based applications, like 16bit gray formats. (since wpf is more new age like design friendly)
maybe try this it works great for me:
http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp?msg=5136670
if its 565 maybe do something like
private Bitmap Convert565bppTo24bpp(Bitmap ConvertMe)
{
Bitmap clone = new Bitmap(ConvertMe.Width, ConvertMe.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);//.Format32bppPArgb);
using (Graphics gr = Graphics.FromImage(clone))
{ gr.DrawImage(ConvertMe, new Rectangle(0, 0, clone.Width, clone.Height)); }
return clone;
}
I have the following code which takes an array of bytes which i generated and writes them out to this bitmap. If i set the pixel format to Format4bppIndexed, then i get a readable image repeating width wise 4 times, if i set it to Format1bppIndexed(which is the correct setting) then i get one big unreadable image.
The image was a decoded Jbig2 image , i know the bytes are correct i can't seem to figure out how to get it into a 1bpp readable format.
Does anyone have any advice on that matter
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format1bppIndexed);
//Create a BitmapData and Lock all pixels to be written
BitmapData bmpData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.WriteOnly, bitmap.PixelFormat);
//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(newarray, 0, bmpData.Scan0, newarray.Length);
//Unlock the pixels
bitmap.UnlockBits(bmpData);
The following may work although, if I remember correctly, Stride sometimes has an effect and a simple block-copy won't suffice (line by line must be used instead).
Bitmap bitmap = new Bitmap(
width,
height,
System.Drawing.PixelFormat.Format16bppGrayScale
);
To handle the Stride you'd want:
BitmapData^ data = bitmap->LockBits(oSize,
ImageLockMode::ReadOnly, bitmap->PixelFormat);
try {
unsigned char *pData = (unsigned char *)data->Scan0.ToPointer();
for( int x = 0; x < bmpImage->Width; ++x )
{
for( int y = 0; y < bmpImage->Height; ++y )
{
// Note: Stride is data width of scan line rounded up
// to 4 byte boundary.
// Requires use of Stride, not (width * pixelWidth)
int ps = y*bmpImage->Width*(nBitsPerPixel / 8)
+ x * (nBitsPerPixel / 8);
int p = y * data->Stride + x * (nBitsPerPixel / 8);
Byte lo = newarray[ps + 1];
Byte hi = newarray[ps + 0];
pData[p + 1] = lo;
pData[p + 0] = hi;
}
}
} finally {
bmpImage->UnlockBits(data);
}
Note: This was written in C++/CLI. Let me know if you need C# equivalents for any of the operations here. (Also, I pulled it from a read from bitmap rather than a write to bitmap so it may yet be a bit rough, but should hopefully give you the idea...)
I figured this out Although i'm still not sure why it should matter.
Based on this stackoverflow posting How can I load the raw data of a 48bpp image into a Bitmap?
I used the WPF classes instead of the GDI and wrote the code like this
var bitmap = new WriteableBitmap(width, height, 96, 96, System.Windows.Media.PixelFormats.BlackWhite, null);
bitmap.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), newarray, stride, 0);
MemoryStream stream3 = new MemoryStream();
var encoder = new TiffBitmapEncoder ();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream3);
This correctly creates the image.
If anyone has any insight into why this might be the case please comment below
The port which now mostly works(lots of cleanup code) was based on a java implementation of JPedal Big2 Decoder to .NET. If anyone knows anyone interested send them here
https://github.com/devteamexpress/JBig2Decoder.NET
MSDN reference: [1] http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx#Y1178
From the link it says that the first argument will "specifies the portion of the Bitmap to lock" which I set to be a smaller part of the Bitmap (Bitmap is 500x500, my rectangle is (0,0,50,50)) however the returned BitmapData has stride of 1500 (=500*3) so basically every scan will still scan through the whole picture horizontally. However, what I want is only the top left 50x50 part of the bitmap.
How does this work out?
The stride will always be of the full bitmap, but the Scan0 property will be different according to the start point of the lock rectangle, as well as the Height and Width of the BitmapData.
The reason for that is that you will still need to know the real bit-width of the bitmap, in order to iterate over the rows (add stride to address).
A simple way to go about it would be:
var bitmap = new Bitmap(100, 100);
var data = bitmap.LockBits(new Rectangle(0, 0, 10, 10),
ImageLockMode.ReadWrite,
bitmap.PixelFormat);
var pt = (byte*)data.Scan0;
var bpp = data.Stride / bitmap.Width;
for (var y = 0; y < data.Height; y++)
{
// This is why real scan-width is important to have!
var row = pt + (y * data.Stride);
for (var x = 0; x < data.Width; x++)
{
var pixel = row + x * bpp;
for (var bit = 0; bit < bpp; bit++)
{
var pixelComponent = pixel[bit];
}
}
}
bitmap.UnlockBits(data);
So it is basically really just locking the whole bitmap, but giving you a pointer to the top-left pixel of the rectangle in the bitmap, and setting the scan's width and height appropriately.
I am opening different types of images like (8 and 16 bit) and they are (Monocrome, RGB ,palette color).
I have raw pixel data of these images.
I create bitmap like this for 8 bit images.
//for monocrome images i am passing PixelFormat.Format8bppIndexed.
//for RGB images i am passing PixelFormat.Format24bppRgb
PixelFormat format = PixelFormat.Format8bppIndexed;
Bitmap bmp = new Bitmap(Img_Width, Img_Height,format);
Rectangle rect = new Rectangle(0, 0, Img_Width, Img_Height);
//locking the bitmap on memory
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
// copy the managed byte array to the bitmap's image data
Marshal.Copy(rawPixel, 0, bmpData.Scan0, rawPixel.Length);
bmp.UnlockBits(bmpData);
The problem is that when i draw that bmp image then it differs in color than original.
So is there any way to apply lut (lookup table) on that colored images.
i want any unsafe code because i tried getixel and setPixel and they are very slow.
I also dont want Image.fromSource() methods.
Take a look at the bitmap's Image.Palette property.
As far as I know, .NET does not support ICC color profiles, so if you for instance open an image that is using the AdobeRGB color profile, the colours will appear a bit duller and more "greyish" than if you open the same image file in, say, Photoshop or another color-profile-aware software.
This post discusses some color profile issues; you may find something of interest there.
GetPixel and SetPixel are indeed very slow. If you want to do operations on single pixels, consider using a FastBitmap. It allows to quickly color pixels. Using this unsafe bitmap will greatly improve your speed.
i solved this problem see how.
Somewhere i read that GDI+ return BGR value not the RGB.
So i reverse the order and amazing everything fine.
But it is little bit slow.
PixelFormat format = PixelFormat.Format8bppIndexed;
Bitmap bmp = new Bitmap(Img_Width, Img_Height,format);
Rectangle rect = new Rectangle(0, 0, Img_Width, Img_Height);
//locking the bitmap on memory
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
Marshal.Copy(rawPixel, 0, bmpData.Scan0, rawPixel.Length);
int stride = bmpData.Stride;
System.IntPtr Scan0 = bmpData.Scan0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
int nOffset = stride - bmp.Width * SAMPLES_PER_PIXEL ;
byte red, green, blue;
for (int y = 0; y < bmp.Height; ++y)
{
for (int x = 0; x < bmp.Width; ++x)
{
blue = p[0];
green = p[1];
red = p[2];
p[0] = red;
p[1] = green;
p[2] = blue;
p += 3;
}
p += nOffset;
}
}
////unlockimg the bitmap
bmp.UnlockBits(bmpData);
thanks
Can anybody is having some faster code than that.