I have a picture containing text :
I made a method to detect text rows. This method return the 4 corners for the text zone (always sorted) :
I want to modify the bitmap to draw a rectangle (with transparence) from theses 4 corners. Something like this :
I have my image in gray scale. I created a function to draw a rectangle, but I only achieve to draw a right rectangle :
public static void SaveDrawRectangle(int width, int height, Byte[] matrix, int dpi, System.Drawing.Point[] corners, string path)
{
System.Windows.Media.Imaging.WriteableBitmap wbm = new System.Windows.Media.Imaging.WriteableBitmap(width, height, dpi, dpi, System.Windows.Media.PixelFormats.Bgra32, null);
uint[] pixels = new uint[width * height];
for (int Y = 0; Y < height; Y++)
{
for (int X = 0; X < width; X++)
{
byte pixel = matrix[Y * width + X];
int red = pixel;
int green = pixel;
int blue = pixel;
int alpha = 255;
if (X >= corners[0].X && X <= corners[1].X &&
Y >= corners[0].Y && Y <= corners[3].Y)
{
red = 255;
alpha = 255;
}
pixels[Y * width + X] = (uint)((alpha << 24) + (red << 16) + (green << 8) + blue);
}
}
wbm.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), pixels, width * 4, 0);
using (FileStream stream5 = new FileStream(path, FileMode.Create))
{
PngBitmapEncoder encoder5 = new PngBitmapEncoder();
encoder5.Frames.Add(BitmapFrame.Create(wbm));
encoder5.Save(stream5);
}
}
How can I draw a rectangle from 4 corners ?
I modify my condition by replacing with that code:
public static void SaveDrawRectangle(int width, int height, Byte[] matrix, int dpi, List<Point> corners, string path)
{
System.Windows.Media.Imaging.WriteableBitmap wbm = new System.Windows.Media.Imaging.WriteableBitmap(width, height, dpi, dpi, System.Windows.Media.PixelFormats.Bgra32, null);
uint[] pixels = new uint[width * height];
for (int Y = 0; Y < height; Y++)
{
for (int X = 0; X < width; X++)
{
byte pixel = matrix[Y * width + X];
int red = pixel;
int green = pixel;
int blue = pixel;
int alpha = 255;
if (IsInRectangle(X, Y, corners))
{
red = 255;
}
pixels[Y * width + X] = (uint)((alpha << 24) + (red << 16) + (green << 8) + blue);
}
}
wbm.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), pixels, width * 4, 0);
using (FileStream stream5 = new FileStream(path, FileMode.Create))
{
PngBitmapEncoder encoder5 = new PngBitmapEncoder();
encoder5.Frames.Add(BitmapFrame.Create(wbm));
encoder5.Save(stream5);
}
}
public static bool IsInRectangle(int X, int Y, List<Point> corners)
{
Point p1, p2;
bool inside = false;
if (corners.Count < 3)
{
return inside;
}
var oldPoint = new Point(
corners[corners.Count - 1].X, corners[corners.Count - 1].Y);
for (int i = 0; i < corners.Count; i++)
{
var newPoint = new Point(corners[i].X, corners[i].Y);
if (newPoint.X > oldPoint.X)
{
p1 = oldPoint;
p2 = newPoint;
}
else
{
p1 = newPoint;
p2 = oldPoint;
}
if ((newPoint.X < X) == (X <= oldPoint.X)
&& (Y - (long)p1.Y) * (p2.X - p1.X)
< (p2.Y - (long)p1.Y) * (X - p1.X))
{
inside = !inside;
}
oldPoint = newPoint;
}
return inside;
}
It works but have 2 failings :
generated images are very big (base image take 6 Mo and after drawing 25 Mo)
generation take several time (my images are 5000x7000 pixels, process take 10 seconds)
There is probably a better way, but this way is working good.
Related
I have an Bitmap with various color patterns and I need to find the bounding rectangles of one given color (For example: Red) within the Bitmap. I found some code to process images but unable to figure out how to achieve this.
Any help would be highly appreciated.
This is my code.
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);
}
Edit: The Bitmap contains solid color shapes, multiple shapes with same color can appear. I need to find the bounding rectangle of each shape.
Just like the paint fills color with bucket tool, I need the bounding rectangle of the filled area.
I can provide x, y coordinates of point on Bitmap to find the bound rectangle of color.
You would do this just like any other code where you want to find the min or max value in a list. With the difference that you want to find both min and max in both X and Y dimensions. Ex:
public static Rectangle GetBounds(this Bitmap bmp, Color color)
{
int minX = int.MaxValue;
int minY = int.MaxValue;
int maxX = int.MinValue;
int maxY = int.MinValue;
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
var c = bmp.GetPixel(x, y);
if (color == c)
{
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
var width = maxX - minX;
var height = maxY - minY;
if (width <= 0 || height <= 0)
{
// Handle case where no color was found, or if color is a single row/column
return default;
}
return new Rectangle(minX, minY, width, height);
}
There are plenty of resources on how to use LockBits/pointers. So converting the code to use this instead of GetPixel is left as an exercise.
If you are not concerned with the performance, and an exact color match is enough for you, then just scan the bitmap:
var l = bmp.Width; var t = bmp.Height; var r = 0; var b = 0;
for (var i = 0; i<rgbValues.Length, i++)
{
if(rgbValues[i] == 255) // rgb representation of red;
{
l = Math.Min(l, i % bmpData.Stride); r = Math.Max(r, i % bmpData.Stride);
t = Math.Min(l, i / bmpData.Stride); b = Math.Max(b, i / bmpData.Stride);
}
}
if(l>=r) // at least one point is found
return new Rectangle(l, t, r-l+1, b-t+1);
else
return new Rectangle(0, 0, 0, 0); // nothing found
You can search for the first point of each shape that fills a different area on the Bitmap, read a single horizontal row to get the points of the given color, then loop vertically within the horizontal range to get the adjacent points.
Once you get all the points of each, you can calculate the bounding rectangle through the first and last points.
public static IEnumerable<Rectangle> GetColorRectangles(Bitmap src, Color color)
{
var rects = new List<Rectangle>();
var points = new List<Point>();
var srcRec = new Rectangle(0, 0, src.Width, src.Height);
var srcData = src.LockBits(srcRec, ImageLockMode.ReadOnly, src.PixelFormat);
var srcBuff = new byte[srcData.Stride * srcData.Height];
var pixSize = Image.GetPixelFormatSize(src.PixelFormat) / 8;
Marshal.Copy(srcData.Scan0, srcBuff, 0, srcBuff.Length);
src.UnlockBits(srcData);
Rectangle GetColorRectangle()
{
var curX = points.First().X;
var curY = points.First().Y + 1;
var maxX = points.Max(p => p.X);
for(var y = curY; y < src.Height; y++)
for(var x = curX; x <= maxX; x++)
{
var pos = (y * srcData.Stride) + (x * pixSize);
var blue = srcBuff[pos];
var green = srcBuff[pos + 1];
var red = srcBuff[pos + 2];
if (Color.FromArgb(red, green, blue).ToArgb().Equals(color.ToArgb()))
points.Add(new Point(x, y));
else
break;
}
var p1 = points.First();
var p2 = points.Last();
return new Rectangle(p1.X, p1.Y, p2.X - p1.X, p2.Y - p1.Y);
}
for (var y = 0; y < src.Height; y++)
{
for (var x = 0; x < src.Width; x++)
{
var pos = (y * srcData.Stride) + (x * pixSize);
var blue = srcBuff[pos];
var green = srcBuff[pos + 1];
var red = srcBuff[pos + 2];
if (Color.FromArgb(red, green, blue).ToArgb().Equals(color.ToArgb()))
{
var p = new Point(x, y);
if (!rects.Any(r => new Rectangle(r.X - 2, r.Y - 2,
r.Width + 4, r.Height + 4).Contains(p)))
points.Add(p);
}
}
if (points.Any())
{
var rect = GetColorRectangle();
rects.Add(rect);
points.Clear();
}
}
return rects;
}
Demo
private IEnumerable<Rectangle> shapesRects = Enumerable.Empty<Rectangle>();
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
var sx = 1f * pictureBox1.Width / pictureBox1.ClientSize.Width;
var sy = 1f * pictureBox1.Height / pictureBox1.ClientSize.Height;
var p = Point.Round(new PointF(e.X * sx, e.Y * sy));
var c = (pictureBox1.Image as Bitmap).GetPixel(p.X, p.Y);
shapesRects = GetColorRectangles(pictureBox1.Image as Bitmap, c);
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (shapesRects.Any())
using (var pen = new Pen(Color.Black, 2))
e.Graphics.DrawRectangles(pen, shapesRects.ToArray());
}
Modifying the code provided in this link:
Original code
I wrote this:
private void btnLoad_Click(object sender, EventArgs e)
{
if (System.IO.File.Exists(txtPicture.Text))
{
byte[] _data = System.IO.File.ReadAllBytes(txtPicture.Text);
var _rgbData = Convert16BitGrayScaleToRgb16(_data, 160, 120);
var _bmp = CreateBitmapFromBytes(_rgbData, 160, 120);
pbFrame.Image = _bmp;
}
}
private static void Convert16bitGSToRGB(UInt16 color, out byte red, out byte green, out byte blue)
{
red = (byte)(color & 0x31);
green = (byte)((color & 0x7E0) >> 5);
blue = (byte)((color & 0xF800) >> 11);
}
private static byte[] Convert16BitGrayScaleToRgb48(byte[] inBuffer, int width, int height)
{
int inBytesPerPixel = 2;
int outBytesPerPixel = 6;
byte[] outBuffer = new byte[width * height * outBytesPerPixel];
int inStride = width * inBytesPerPixel;
int outStride = width * outBytesPerPixel;
// Step through the image by row
for (int y = 0; y < height; y++)
{
// Step through the image by column
for (int x = 0; x < width; x++)
{
// Get inbuffer index and outbuffer index
int inIndex = (y * inStride) + (x * inBytesPerPixel);
int outIndex = (y * outStride) + (x * outBytesPerPixel);
byte hibyte = inBuffer[inIndex + 1];
byte lobyte = inBuffer[inIndex];
//R
outBuffer[outIndex] = lobyte;
outBuffer[outIndex + 1] = hibyte;
//G
outBuffer[outIndex + 2] = lobyte;
outBuffer[outIndex + 3] = hibyte;
//B
outBuffer[outIndex + 4] = lobyte;
outBuffer[outIndex + 5] = hibyte;
}
}
return outBuffer;
}
private static byte[] Convert16BitGrayScaleToRgb16(byte[] inBuffer, int width, int height)
{
int inBytesPerPixel = 2;
int outBytesPerPixel = 2;
byte[] outBuffer = new byte[width * height * outBytesPerPixel];
int inStride = width * inBytesPerPixel;
int outStride = width * outBytesPerPixel;
// Step through the image by row
for (int y = 0; y < height; y++)
{
// Step through the image by column
for (int x = 0; x < width; x++)
{
// Get inbuffer index and outbuffer index
int inIndex = (y * inStride) + (x * inBytesPerPixel);
int outIndex = (y * outStride) + (x * outBytesPerPixel);
byte hibyte = inBuffer[inIndex];
byte lobyte = inBuffer[inIndex+1];
outBuffer[outIndex] = lobyte;
outBuffer[outIndex+1] = hibyte;
}
}
return outBuffer;
}
private static byte[] Convert16BitGrayScaleToRgb24(byte[] inBuffer, int width, int height)
{
int inBytesPerPixel = 2;
int outBytesPerPixel = 3;
byte[] outBuffer = new byte[width * height * outBytesPerPixel];
int inStride = width * inBytesPerPixel;
int outStride = width * outBytesPerPixel;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int inIndex = (y * inStride) + (x * inBytesPerPixel);
int outIndex = (y * outStride) + (x * outBytesPerPixel);
byte hibyte = inBuffer[inIndex];
byte lobyte = inBuffer[inIndex + 1];
byte r, g, b;
UInt16 color = (UInt16)(hibyte << 8 | lobyte);
Convert16bitGSToRGB(color, out r, out g, out b);
outBuffer[outIndex] = r;
outBuffer[outIndex + 1] = g;
outBuffer[outIndex + 2] = b;
}
}
return outBuffer;
}
private static Bitmap CreateBitmapFromBytes(byte[] pixelValues, int width, int height)
{
//Create an image that will hold the image data
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format16bppRgb565);
//Get a reference to the images pixel data
Rectangle dimension = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData picData = bmp.LockBits(dimension, ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr pixelStartAddress = picData.Scan0;
//Copy the pixel data into the bitmap structure
Marshal.Copy(pixelValues, 0, pixelStartAddress, pixelValues.Length);
bmp.UnlockBits(picData);
return bmp;
}
But still the result of the conversion is not satisfying/correct. This's the picture I should get:
Converting the file linked here:
Example RAW16 picture file
This's the result using Convert16BitGrayScaleToRgb48:
This's the result using Convert16BitGrayScaleToRgb16:
This's the result using Convert16BitGrayScaleToRgb24:
It's quite clear that the color remapping is wrong but I cant understand where the problem is.
Additionally I also found that picturebox didn't show exactly what it stores. The second image from the top (Convert16BitGrayScaleToRgb48 result) is what the picturebox shows while the following picture is what I obtain if I save the image shown in PNG format:
I tought RAW16 grayscale should mean 2 bytes containing either a 16 bit gray value or an RGB gray value encoded on a 565 or 555 map. But none of those hypotesis seems to match the real thing.
Someone has an hint on how to convert the value provided in the source file to obtain a picture like the first one (obtained from the same source using ImageJ)?
I found a possibile hint using GIMP. If I load the original file trough this app (changing extension in .data and/or forcing to load it as RAW) and setting it as a 160x120 16bpp BigEndian I got a nearly black frame (!), but if I change levels compressing the range around the only small peak present (around 12,0 black - 13,0 white) the image result correct. Changing endianism is pretty straightforward compressing the dynamic range a little less but I'm working on it.
The first lesson learned in this experience is "Don't trust your eyes" :-).
The final result of my efforts are these three methods:
public static void GetMinMax(byte[] data, out UInt16 min, out UInt16 max, bool big_endian = true)
{
if (big_endian)
min = max = (UInt16)((data[0] << 8) | data[1]);
else
min = max = (UInt16)((data[1] << 8) | data[0]);
for (int i = 0; i < (data.Length - 1); i += 2)
{
UInt16 _value;
if (big_endian)
_value = (UInt16)((data[i] << 8) | data[i + 1]);
else
_value = (UInt16)((data[i + 1] << 8) | data[i]);
if (_value < min)
min = _value;
if (_value > max)
max = _value;
}
}
public static void CompressRange(byte MSB, byte LSB, UInt16 min, UInt16 max, out byte color, Polarity polarity)
{
UInt16 _value = (UInt16)((MSB << 8) | LSB);
_value -= min;
switch (polarity)
{
case Polarity.BlackHot:
_value = (UInt16)((_value * 255) / (max - min));
_value = (UInt16)(255 - _value);
break;
default:
case Polarity.WhiteHot:
_value = (UInt16)((_value * 255) / (max - min));
break;
}
color = (byte)(_value & 0xff);
}
public static byte[] Convert16BitGrayScaleToRgb24(byte[] inBuffer, int width, int height, UInt16 min, UInt16 max, bool big_endian = true, Polarity polarity = Polarity.WhiteHot)
{
int inBytesPerPixel = 2;
int outBytesPerPixel = 3;
byte[] outBuffer = new byte[width * height * outBytesPerPixel];
int inStride = width * inBytesPerPixel;
int outStride = width * outBytesPerPixel;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int inIndex = (y * inStride) + (x * inBytesPerPixel);
int outIndex = (y * outStride) + (x * outBytesPerPixel);
byte hibyte;
byte lobyte;
if (big_endian)
{
hibyte = inBuffer[inIndex];
lobyte = inBuffer[inIndex + 1];
}
else
{
hibyte = inBuffer[inIndex + 1];
lobyte = inBuffer[inIndex];
}
byte gray;
CompressRange(hibyte, lobyte, min, max, out gray, polarity);
outBuffer[outIndex] = gray;
outBuffer[outIndex + 1] = gray;
outBuffer[outIndex + 2] = gray;
}
}
return outBuffer;
}
These allows to load the file attached to the original question and display it on a standard WindowsForm PictureBox. Using 48bpp format will result in a degraded image on some graphic cards (at least on mine).
BTW GetMinMax calculate min max value on the current frame regardless of the history of the environment. This means that if you are going to use this functions to display a picture sequence (as I am) a strong variation of average temperature in the FOV will drive the overall image to a different exposure resulting in loosing some details of the picture. In such cases I suggest to calculate min-max over the current frame but NON to use it in Convert16BitGrayScaleToRgb24 using instead a moving average for both values.
I'm trying to implement an Image Edge Detection into a WPF program.
I already have it working, but the converting of the image is quite slow.
The code is not using the slow GetPixel and SetPixel functions. But instead I'm looping through the image in some unsafe code so that I can directly access the value's using a pointer.
Before starting the Edge detection I'm also converting the image to a greyscale image to improve the edge detection speed.
But still it takes the program around 1600ms to convert an image with a size of 1920x1440 pixels, which I think could be much faster.
This is the original image:
Which is converted to this (Snapshot of the application):
This is how I'm converting the image, I'm wondering what I can do to get to some other speed improvements?
Loading the image and create a Greyscale WriteableBitmap:
private void imageData_Loaded(object sender, RoutedEventArgs e)
{
if (imageData.Source != null)
{
BitmapSource BitmapSrc = new FormatConvertedBitmap(imageData.Source as BitmapSource, PixelFormats.Gray8 /* Convert to greyscale image */, null, 0);
writeableOriginalBitmap = new WriteableBitmap(BitmapSrc);
writeableBitmap = writeableOriginalBitmap.Clone();
imageData.Source = writeableBitmap;
EdgeDetection();
}
}
Converting the Image:
private const int TOLERANCE = 20;
private void EdgeDetection()
{
DateTime startTime = DateTime.Now; //Save starting time
writeableOriginalBitmap.Lock();
writeableBitmap.Lock();
unsafe
{
byte* pBuffer = (byte*)writeableBitmap.BackBuffer.ToPointer();
byte* pOriginalBuffer = (byte*)writeableOriginalBitmap.BackBuffer.ToPointer();
for (int row = 0; row < writeableOriginalBitmap.PixelHeight; row++)
{
for (int column = 0; column < writeableOriginalBitmap.PixelWidth; column++)
{
byte edgeColor = getEdgeColor(column, row, pOriginalBuffer); //Get pixel color based on edge value
pBuffer[column + (row * writeableBitmap.BackBufferStride)] = (byte)(255 - edgeColor);
}
}
}
//Refresh image
writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight));
writeableBitmap.Unlock();
writeableOriginalBitmap.Unlock();
//Calculate converting time
TimeSpan diff = DateTime.Now - startTime;
Debug.WriteLine("Loading Time: " + (int)diff.TotalMilliseconds);
}
private unsafe byte getEdgeColor(int xPos, int yPos, byte* pOriginalBuffer)
{
byte Color;
byte maxColor = 0;
byte minColor = 255;
int difference;
//Calculate max and min value of surrounding pixels
for (int y = yPos - 1; y <= yPos + 1; y++)
{
for (int x = xPos - 1; x <= xPos + 1; x++)
{
if (x >= 0 && x < writeableOriginalBitmap.PixelWidth && y >= 0 && y < writeableOriginalBitmap.PixelHeight)
{
Color = pOriginalBuffer[x + (y * writeableOriginalBitmap.BackBufferStride)];
if (Color > maxColor) //If current pixel has higher value as previous max pixel
maxColor = Color; //Save current pixel value as max
if (Color < minColor) //If current pixel has lower value as previous min pixel
minColor = Color; //Save current pixel value as min
}
}
}
//Difference of minimum and maximum pixel with tollerance
difference = maxColor - minColor - TOLERANCE;
if (difference < 0)
difference = 0;
return (byte)difference;
}
Console Output:
Loading Time: 1599
The following code runs your algorithm on a byte array instead of the BackBuffer of a WriteableBitmap. It completes in less than 300 ms with a 1900x1200 image on my PC.
private static BitmapSource EdgeDetection(BitmapSource source)
{
var stopwatch = Stopwatch.StartNew();
var bitmap = new FormatConvertedBitmap(source, PixelFormats.Gray8, null, 0);
var width = bitmap.PixelWidth;
var height = bitmap.PixelHeight;
var originalBuffer = new byte[width * height];
var buffer = new byte[width * height];
bitmap.CopyPixels(originalBuffer, width, 0);
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
byte edgeColor = GetEdgeColor(originalBuffer, width, height, x, y);
buffer[width * y + x] = (byte)(255 - edgeColor);
}
}
Debug.WriteLine(stopwatch.ElapsedMilliseconds);
return BitmapSource.Create(
width, height, 96, 96, PixelFormats.Gray8, null, buffer, width);
}
private static byte GetEdgeColor(byte[] buffer, int width, int height, int x, int y)
{
const int tolerance = 20;
byte minColor = 255;
byte maxColor = 0;
var xStart = Math.Max(0, x - 1);
var xEnd = Math.Min(width - 1, x + 1);
var yStart = Math.Max(0, y - 1);
var yEnd = Math.Min(height - 1, y + 1);
for (var j = yStart; j <= yEnd; j++)
{
for (var i = xStart; i <= xEnd; i++)
{
var color = buffer[width * j + i];
minColor = Math.Min(minColor, color);
maxColor = Math.Max(maxColor, color);
}
}
return (byte)Math.Max(0, maxColor - minColor - tolerance);
}
I'm trying to find the needle from these or similar pictures:
My solution is take average brightness of picture and set black and white pixels depends on it. The result is something like this:
I dont need to see numbers and staf there.. only needle but its not big problem when its there. But im using set, get pixel functions and its realy slow i reed something about LockBits metod, i use it for get brightness but i dont know how to use it correct for setpixel. Can anyone help me with my code?..thnx
BitmapData imageData = imgPristroj.LockBits(new Rectangle(0, 0, imgPristroj.Width, imgPristroj.Height), ImageLockMode.ReadOnly, imgPristroj.PixelFormat);
float brightness = 0;
float average;
unsafe
{
try
{
UnmanagedImage Unimg = new UnmanagedImage(imageData);
int pixelSize = (Unimg.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
byte* p = (byte*)Unimg.ImageData.ToPointer();
for (int y = 0; y < Unimg.Height; y++)
{
for (int x = 0; x < Unimg.Width; x++, p += pixelSize)
{
brightness += Unimg.GetPixel(x, y).GetBrightness();
}
}
average = brightness / (Unimg.Width * Unimg.Height);
}
finally
{
imgPristroj.UnlockBits(imageData); //Unlock
}
}
img19 = (Bitmap)imgPristroj.Clone();
for (int y = 0; y < img19.Height; y++)
{
for (int x = 0; x < img19.Width; x++)
{
if (img19.GetPixel(x, y).GetBrightness() > average)
{
img19.SetPixel(x, y, Color.White);
}
else
{
img19.SetPixel(x, y, Color.Black);
}
}
}
Edit2: This is my whole code..
float brightness = 0;
float average = 0;
PixelUtil pixelUtil2 = new PixelUtil((Bitmap)imgPristroj.Clone());
pixelUtil2.LockBits();
for (int y = 0; y < imgPristroj.Height; y++)
{
// for each pixel
for (int x = 0; x < imgPristroj.Width; x++)
{
brightness += pixelUtil2.GetPixel(x, y).GetBrightness();
}
}
average = brightness / (imgPristroj.Width * imgPristroj.Height);
pixelUtil2.UnlockBits();
img19 = (Bitmap)imgPristroj.Clone();
Crop cfilter1 = new Crop(new Rectangle(0, (int)(pix * 1.6), img19.Width, (int)(pix * 3)));
img19 = cfilter1.Apply(img19);
PixelUtil pixelUtil = new PixelUtil(img19);
pixelUtil.LockBits();
for (int y = 0; y < img19.Height; y++)
{
for (int x = 0; x < img19.Width; x++)
{
if (pixelUtil.GetPixel(x, y).GetBrightness() >= average)
{
pixelUtil.SetPixel(x, y, Color.White);
}
else
{
pixelUtil.SetPixel(x, y, Color.Black);
}
}
}
pixelUtil.UnlockBits();
string filepath = Environment.CurrentDirectory;
string fileName = System.IO.Path.Combine(filepath, #"img" + ".bmp");
img19.Save(fileName);
I get this bitmap with color pixels, can you tell me why?
And when i use red color.. not black... (pixelUtil.SetPixel(x, y, Color.Red);) i have got this funny pic. (differnt size is OK..)
You can try using marshaling: It's quite fast. (You just need to copy-paste this)
public class PixelUtil
{
Bitmap source = null;
IntPtr Iptr = IntPtr.Zero;
BitmapData bitmapData = null;
public byte[] Pixels { get; set; }
public int Depth { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
/// <summary>
/// Pixel marshaling class, use this to get and set pixels rapidly.
/// </summary>
/// <param name="source">The Bitmap to work with</param>
public PixelUtil(Bitmap source)
{
this.source = source;
}
/// <summary>
/// Lock bitmap data
/// </summary>
public void LockBits()
{
try
{
// Get width and height of bitmap
Width = source.Width;
Height = source.Height;
// get total locked pixels count
int PixelCount = Width * Height;
// Create rectangle to lock
var rect = new Rectangle(0, 0, Width, Height);
// get source bitmap pixel format size
Depth = System.Drawing.Image.GetPixelFormatSize(source.PixelFormat);
// Check if bpp (Bits Per Pixel) is 8, 24, or 32
if (Depth != 8 && Depth != 24 && Depth != 32)
{
throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
}
// Lock bitmap and return bitmap data
bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite,
source.PixelFormat);
// create byte array to copy pixel values
int step = Depth / 8;
Pixels = new byte[PixelCount * step];
Iptr = bitmapData.Scan0;
// Copy data from pointer to array
Marshal.Copy(Iptr, Pixels, 0, Pixels.Length);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Unlock bitmap data
/// </summary>
public void UnlockBits()
{
try
{
// Copy data from byte array to pointer
Marshal.Copy(Pixels, 0, Iptr, Pixels.Length);
// Unlock bitmap data
source.UnlockBits(bitmapData);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get the color of the specified pixel
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public Color GetPixel(int x, int y)
{
Color clr = Color.Empty;
// Get color components count
int cCount = Depth / 8;
// Get start index of the specified pixel
int i = ((y * Width) + x) * cCount;
if (i > Pixels.Length - cCount)
throw new IndexOutOfRangeException();
if (Depth == 32) //For 32 bpp get Red, Green, Blue and Alpha
{
byte b = Pixels[i];
byte g = Pixels[i + 1];
byte r = Pixels[i + 2];
byte a = Pixels[i + 3]; // a
clr = Color.FromArgb(a, r, g, b);
}
if (Depth == 24) //For 24 bpp get Red, Green and Blue
{
byte b = Pixels[i];
byte g = Pixels[i + 1];
byte r = Pixels[i + 2];
clr = Color.FromArgb(r, g, b);
}
if (Depth == 8) //For 8 bpp get color value (Red, Green and Blue values are the same)
{
byte c = Pixels[i];
clr = Color.FromArgb(c, c, c);
}
return clr;
}
/// <summary>
/// Set the color of the specified pixel
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="color"></param>
public void SetPixel(int x, int y, Color color)
{
//Get color components count
int cCount = Depth / 8;
//Get start index of the specified pixel
int i = ((y * Width) + x) * cCount;
if (Depth == 32) //For 32 bpp set Red, Green, Blue and Alpha
{
Pixels[i] = color.B;
Pixels[i + 1] = color.G;
Pixels[i + 2] = color.R;
Pixels[i + 3] = color.A;
}
if (Depth == 24) //For 24 bpp set Red, Green and Blue
{
Pixels[i] = color.B;
Pixels[i + 1] = color.G;
Pixels[i + 2] = color.R;
}
if (Depth == 8) //For 8 bpp set color value (Red, Green and Blue values are the same)
{
Pixels[i] = color.B;
}
}
}
You can call like this:
public void Example(Bitmap image)
{
PixelUtil pixelUtil = new PixelUtil(image);
pixelUtil.LockBits();
Color firstPixel = pixelUtil.GetPixel(0, 0);
pixelUtil.SetPixel(0, 0, Color.White);
//Don't forget to unlock!
pixelUtil.UnlockBits();
}
EDIT:
Not sure how are you saving the image, but it Works fine for me:
public Form1()
{
InitializeComponent();
Bitmap image1 = new Bitmap(#"C:\Users\Nicke Manarin\Desktop\YEeJO.png");
BlackWhite(image1);
}
public void BlackWhite(Bitmap image)
{
PixelUtil pixelUtil = new PixelUtil(image);
pixelUtil.LockBits();
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
if (pixelUtil.GetPixel(x, y).GetBrightness() > 0.5)
{
pixelUtil.SetPixel(x, y, Color.White);
}
else
{
pixelUtil.SetPixel(x, y, Color.Black);
}
}
}
pixelUtil.UnlockBits();
pictureBox1.Image = image;
image.Save(#"C:\Users\Nicke Manarin\Desktop\YEeJO2.png");
}
I use this code and now its working good.... thnx again !!!!
public class PointBitmap
{
Bitmap source = null;
IntPtr Iptr = IntPtr.Zero;
BitmapData bitmapData = null;
public int Depth { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public PointBitmap(Bitmap source)
{
this.source = source;
}
public void LockBits()
{
try
{
// Get width and height of bitmap
Width = source.Width;
Height = source.Height;
// get total locked pixels count
int PixelCount = Width * Height;
// Create rectangle to lock
Rectangle rect = new Rectangle(0, 0, Width, Height);
// get source bitmap pixel format size
Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat);
// Check if bpp (Bits Per Pixel) is 8, 24, or 32
if (Depth != 8 && Depth != 24 && Depth != 32)
{
throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
}
// Lock bitmap and return bitmap data
bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite,
source.PixelFormat);
unsafe
{
Iptr = bitmapData.Scan0;
}
}
catch (Exception ex)
{
throw ex;
}
}
public void UnlockBits()
{
try
{
source.UnlockBits(bitmapData);
}
catch (Exception ex)
{
throw ex;
}
}
public Color GetPixel(int x, int y)
{
unsafe
{
byte* ptr = (byte*)Iptr;
ptr = ptr + bitmapData.Stride * y;
ptr += Depth * x / 8;
Color c = Color.Empty;
if (Depth == 32)
{
int a = ptr[3];
int r = ptr[2];
int g = ptr[1];
int b = ptr[0];
c = Color.FromArgb(a, r, g, b);
}
else if (Depth == 24)
{
int r = ptr[2];
int g = ptr[1];
int b = ptr[0];
c = Color.FromArgb(r, g, b);
}
else if (Depth == 8)
{
int r = ptr[0];
c = Color.FromArgb(r, r, r);
}
return c;
}
}
public void SetPixel(int x, int y, Color c)
{
unsafe
{
byte* ptr = (byte*)Iptr;
ptr = ptr + bitmapData.Stride * y;
ptr += Depth * x / 8;
if (Depth == 32)
{
ptr[3] = c.A;
ptr[2] = c.R;
ptr[1] = c.G;
ptr[0] = c.B;
}
else if (Depth == 24)
{
ptr[2] = c.R;
ptr[1] = c.G;
ptr[0] = c.B;
}
else if (Depth == 8)
{
ptr[2] = c.R;
ptr[1] = c.G;
ptr[0] = c.B;
}
}
}
}
i think only difference here is Unsafe modifier
Suppose I have a System.Drawing.Bitmap in 32bpp ARGB mode. It's a large bitmap, but it's mostly fully transparent pixels with a relatively small image somewhere in the middle.
What is a fast algorithm to detect the borders of the "real" image, so I can crop away all the transparent pixels from around it?
Alternatively, is there a function already in .Net that I can use for this?
The basic idea is to check every pixel of the image to find the top, left, right and bottom bounds of the image. To do this efficiently, don't use the GetPixel method, which is pretty slow. Use LockBits instead.
Here's the implementation I came up with:
static Bitmap TrimBitmap(Bitmap source)
{
Rectangle srcRect = default(Rectangle);
BitmapData data = null;
try
{
data = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] buffer = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);
int xMin = int.MaxValue;
int xMax = 0;
int yMin = int.MaxValue;
int yMax = 0;
for (int y = 0; y < data.Height; y++)
{
for (int x = 0; x < data.Width; x++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
if (x < xMin) xMin = x;
if (x > xMax) xMax = x;
if (y < yMin) yMin = y;
if (y > yMax) yMax = y;
}
}
}
if (xMax < xMin || yMax < yMin)
{
// Image is empty...
return null;
}
srcRect = Rectangle.FromLTRB(xMin, yMin, xMax, yMax);
}
finally
{
if (data != null)
source.UnlockBits(data);
}
Bitmap dest = new Bitmap(srcRect.Width, srcRect.Height);
Rectangle destRect = new Rectangle(0, 0, srcRect.Width, srcRect.Height);
using (Graphics graphics = Graphics.FromImage(dest))
{
graphics.DrawImage(source, destRect, srcRect, GraphicsUnit.Pixel);
}
return dest;
}
It can probably be optimized, but I'm not a GDI+ expert, so it's the best I can do without further research...
EDIT: actually, there's a simple way to optimize it, by not scanning some parts of the image :
scan left to right until you find a non-transparent pixel; store (x, y) into (xMin, yMin)
scan top to bottom until you find a non-transparent pixel (only for x >= xMin); store y into yMin
scan right to left until you find a non-transparent pixel (only for y >= yMin); store x into xMax
scan bottom to top until you find a non-transparent pixel (only for xMin <= x <= xMax); store y into yMax
EDIT2: here's an implementation of the approach above:
static Bitmap TrimBitmap(Bitmap source)
{
Rectangle srcRect = default(Rectangle);
BitmapData data = null;
try
{
data = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] buffer = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);
int xMin = int.MaxValue,
xMax = int.MinValue,
yMin = int.MaxValue,
yMax = int.MinValue;
bool foundPixel = false;
// Find xMin
for (int x = 0; x < data.Width; x++)
{
bool stop = false;
for (int y = 0; y < data.Height; y++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
xMin = x;
stop = true;
foundPixel = true;
break;
}
}
if (stop)
break;
}
// Image is empty...
if (!foundPixel)
return null;
// Find yMin
for (int y = 0; y < data.Height; y++)
{
bool stop = false;
for (int x = xMin; x < data.Width; x++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
yMin = y;
stop = true;
break;
}
}
if (stop)
break;
}
// Find xMax
for (int x = data.Width - 1; x >= xMin; x--)
{
bool stop = false;
for (int y = yMin; y < data.Height; y++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
xMax = x;
stop = true;
break;
}
}
if (stop)
break;
}
// Find yMax
for (int y = data.Height - 1; y >= yMin; y--)
{
bool stop = false;
for (int x = xMin; x <= xMax; x++)
{
byte alpha = buffer[y * data.Stride + 4 * x + 3];
if (alpha != 0)
{
yMax = y;
stop = true;
break;
}
}
if (stop)
break;
}
srcRect = Rectangle.FromLTRB(xMin, yMin, xMax, yMax);
}
finally
{
if (data != null)
source.UnlockBits(data);
}
Bitmap dest = new Bitmap(srcRect.Width, srcRect.Height);
Rectangle destRect = new Rectangle(0, 0, srcRect.Width, srcRect.Height);
using (Graphics graphics = Graphics.FromImage(dest))
{
graphics.DrawImage(source, destRect, srcRect, GraphicsUnit.Pixel);
}
return dest;
}
There won't be a significant gain if the non-transparent part is small of course, since it will still scan most of the pixels. But if it's big, only the rectangles around the non-transparent part will be scanned.
I would like to suggest a divide & conquer approach:
split the image in the middle (e.g. vertically)
check if there are non-transparent pixels on the cut line (if so, remember min/max for bounding box)
split left half again vertically
if cut line contains non-transparent pixels -> update bounding box
if not, you can probably discard the leftmost half (I don't know the pictures)
continue with the left-right half (you stated that the image is somewhere in the middle) until you find the leftmost bound of the image
do the same for the right half