EmguCV - Convert color image to rg chromaticity - c#

Does EmguCV provide any built-in function for converting a color image into RG Chromaticity (see Wikipedia link) ?
Thanks in advance.

I could not find any built-in method in EmguCV at least on v3.1 . So , I ended up doing the old way.
Image<Bgr, Byte> img_live = Live_Mat.ToImage<Bgr, Byte>();
for (int i = 0; i < Live_Mat.Height; i++)
{
for (int j = 0; j < Live_Mat.Width; j++)
{
float blue = img_live.Data[i, j, 0];
float green = img_live.Data[i, j, 1];
float red = img_live.Data[i, j, 2];
double sum = red + blue + green;
double r = red / sum;
double g = green / sum;
double b = blue / sum;
if (sum == 0)
{
r = 0;
g = 0;
b = 0;
}
img_live.Data[i, j, 0] = System.Convert.ToByte(Math.Round((b * AWB_rgb_mult), 0));
img_live.Data[i, j, 1] = System.Convert.ToByte(Math.Round((g * AWB_rgb_mult), 0));
img_live.Data[i, j, 2] = System.Convert.ToByte(Math.Round((r * AWB_rgb_mult), 0));
}

Related

How to convert gray image into colormap

enter image description here
i have a color feet image, it transform to grayscale, and then to colormap (jet)
i did it in emgucv, but the color doesnt look so diferent, i need that the result image like the second (only 4-6 color, red, orange*, yellow, green, blue, purple*)
it is possible?
i already try on emgucv and read something gdi+, but i dont understand, i just begin to program
i try this but the color are the same, just more pixel, no gradient
int divideWith = 48;
byte[] table = new byte[256];
for (int i = 0; i < 256; i++)
{
table[i] = (byte)(divideWith * (i / divideWith));
}
Mat mat = ConvertBitmapToMat(rgb);
//_Stopwatch.Reset();
int rows = mat.Rows;
int cols = mat.Cols;
byte[,,] data = mat.ToImage<Bgr, byte>().Data;
byte[,,] resData = new byte[rows, cols, 3];
Parallel.For(0, rows, i =>
{
for (int j = 0; j < cols; j++)
{
resData[i, j, 0] = table[data[i, j, 0]];
resData[i, j, 1] = table[data[i, j, 1]];
resData[i, j, 2] = table[data[i, j, 2]];
}
});
Image<Bgr, byte> resImg = new Image<Bgr, byte>(resData);
Bitmap im = resImg.ToBitmap();
pictureBox2.Image = im;

Image convolution in spatial domain

I am trying to replicate the outcome of this link using linear convolution in spatial-domain.
Images are first converted to 2d double arrays and then convolved. Image and kernel are of the same size. The image is padded before convolution and cropped accordingly after the convolution.
As compared to the FFT-based convolution, the output is weird and incorrect.
How can I solve the issue?
Note that I obtained the following image output from Matlab which matches my C# FFT output:
.
Update-1: Following #Ben Voigt's comment, I changed the Rescale() function to replace 255.0 with 1 and thus the output is improved substantially. But, still, the output doesn't match the FFT output (which is the correct one).
.
Update-2: Following #Cris Luengo's comment, I have padded the image by stitching and then performed spatial convolution. The outcome has been as follows:
So, the output is worse than the previous one. But, this has a similarity with the 2nd output of the linked answer which means a circular convolution is not the solution.
.
Update-3: I have used the Sum() function proposed by #Cris Luengo's answer. The result is a more improved version of **Update-1**:
But, it is still not 100% similar to the FFT version.
.
Update-4: Following #Cris Luengo's comment, I have subtracted the two outcomes to see the difference:
,
1. spatial minus frequency domain
2. frequency minus spatial domain
Looks like, the difference is substantial which means, spatial convolution is not being done correctly.
.
Source Code:
(Notify me if you need more source code to see.)
public static double[,] LinearConvolutionSpatial(double[,] image, double[,] mask)
{
int maskWidth = mask.GetLength(0);
int maskHeight = mask.GetLength(1);
double[,] paddedImage = ImagePadder.Pad(image, maskWidth);
double[,] conv = Convolution.ConvolutionSpatial(paddedImage, mask);
int cropSize = (maskWidth/2);
double[,] cropped = ImageCropper.Crop(conv, cropSize);
return conv;
}
static double[,] ConvolutionSpatial(double[,] paddedImage1, double[,] mask1)
{
int imageWidth = paddedImage1.GetLength(0);
int imageHeight = paddedImage1.GetLength(1);
int maskWidth = mask1.GetLength(0);
int maskHeight = mask1.GetLength(1);
int convWidth = imageWidth - ((maskWidth / 2) * 2);
int convHeight = imageHeight - ((maskHeight / 2) * 2);
double[,] convolve = new double[convWidth, convHeight];
for (int y = 0; y < convHeight; y++)
{
for (int x = 0; x < convWidth; x++)
{
int startX = x;
int startY = y;
convolve[x, y] = Sum(paddedImage1, mask1, startX, startY);
}
}
Rescale(convolve);
return convolve;
}
static double Sum(double[,] paddedImage1, double[,] mask1, int startX, int startY)
{
double sum = 0;
int maskWidth = mask1.GetLength(0);
int maskHeight = mask1.GetLength(1);
for (int y = startY; y < (startY + maskHeight); y++)
{
for (int x = startX; x < (startX + maskWidth); x++)
{
double img = paddedImage1[x, y];
double msk = mask1[x - startX, y - startY];
sum = sum + (img * msk);
}
}
return sum;
}
static void Rescale(double[,] convolve)
{
int imageWidth = convolve.GetLength(0);
int imageHeight = convolve.GetLength(1);
double maxAmp = 0.0;
for (int j = 0; j < imageHeight; j++)
{
for (int i = 0; i < imageWidth; i++)
{
maxAmp = Math.Max(maxAmp, convolve[i, j]);
}
}
double scale = 1.0 / maxAmp;
for (int j = 0; j < imageHeight; j++)
{
for (int i = 0; i < imageWidth; i++)
{
double d = convolve[i, j] * scale;
convolve[i, j] = d;
}
}
}
public static Bitmap ConvolveInFrequencyDomain(Bitmap image1, Bitmap kernel1)
{
Bitmap outcome = null;
Bitmap image = (Bitmap)image1.Clone();
Bitmap kernel = (Bitmap)kernel1.Clone();
//linear convolution: sum.
//circular convolution: max
uint paddedWidth = Tools.ToNextPow2((uint)(image.Width + kernel.Width));
uint paddedHeight = Tools.ToNextPow2((uint)(image.Height + kernel.Height));
Bitmap paddedImage = ImagePadder.Pad(image, (int)paddedWidth, (int)paddedHeight);
Bitmap paddedKernel = ImagePadder.Pad(kernel, (int)paddedWidth, (int)paddedHeight);
Complex[,] cpxImage = ImageDataConverter.ToComplex(paddedImage);
Complex[,] cpxKernel = ImageDataConverter.ToComplex(paddedKernel);
// call the complex function
Complex[,] convolve = Convolve(cpxImage, cpxKernel);
outcome = ImageDataConverter.ToBitmap(convolve);
outcome = ImageCropper.Crop(outcome, (kernel.Width/2)+1);
return outcome;
}
Your current output looks more like the auto-correlation function than the convolution of Lena with herself. I think the issue might be in your Sum function.
If you look at the definition of the convolution sum, you'll see that the kernel (or the image, doesn't matter) is mirrored:
sum_m( f[n-m] g[m] )
For the one function, m appears with a plus sign, and for the other it appears with a minus sign.
You'll need to modify your Sum function to read the mask1 image in the right order:
static double Sum(double[,] paddedImage1, double[,] mask1, int startX, int startY)
{
double sum = 0;
int maskWidth = mask1.GetLength(0);
int maskHeight = mask1.GetLength(1);
for (int y = startY; y < (startY + maskHeight); y++)
{
for (int x = startX; x < (startX + maskWidth); x++)
{
double img = paddedImage1[x, y];
double msk = mask1[maskWidth - x + startX - 1, maskHeight - y + startY - 1];
sum = sum + (img * msk);
}
}
return sum;
}
The other option is to pass a mirrored version of mask1 to this function.
I have found the solution from this link. The main clue was to introduce an offset and a factor.
factor is the sum of all values in the kernel.
offset is an arbitrary value to fix the output further.
.
#Cris Luengo's answer also raised a valid point.
.
The following source code is supplied in the given link:
private void SafeImageConvolution(Bitmap image, ConvMatrix fmat)
{
//Avoid division by 0
if (fmat.Factor == 0)
return;
Bitmap srcImage = (Bitmap)image.Clone();
int x, y, filterx, filtery;
int s = fmat.Size / 2;
int r, g, b;
Color tempPix;
for (y = s; y < srcImage.Height - s; y++)
{
for (x = s; x < srcImage.Width - s; x++)
{
r = g = b = 0;
// Convolution
for (filtery = 0; filtery < fmat.Size; filtery++)
{
for (filterx = 0; filterx < fmat.Size; filterx++)
{
tempPix = srcImage.GetPixel(x + filterx - s, y + filtery - s);
r += fmat.Matrix[filtery, filterx] * tempPix.R;
g += fmat.Matrix[filtery, filterx] * tempPix.G;
b += fmat.Matrix[filtery, filterx] * tempPix.B;
}
}
r = Math.Min(Math.Max((r / fmat.Factor) + fmat.Offset, 0), 255);
g = Math.Min(Math.Max((g / fmat.Factor) + fmat.Offset, 0), 255);
b = Math.Min(Math.Max((b / fmat.Factor) + fmat.Offset, 0), 255);
image.SetPixel(x, y, Color.FromArgb(r, g, b));
}
}
}

Draw rotated sine image

I'm working with 2D Fourier transforms, and I have a method that will output the following result:
The code looks like this:
private Bitmap PaintSin(int s, int n)
{
Data = new int[Width, Height];
Bitmap buffer = new Bitmap(Width, Height);
double inner = (2 * Math.PI * s) / n;
BitmapData originalData = buffer.LockBits(
new Rectangle(0, 0, buffer.Width, buffer.Height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
for (int i = 0; i < buffer.Width; i++)
{
for (int j = 0; j < buffer.Height; j++)
{
double val;
int c = 0;
if (j == 0)
{
val = Math.Sin(inner * i);
val += 1;
val *= 128;
val = val > 255 ? 255 : val;
c = (int)val;
Color col = Color.FromArgb(c, c, c);
SetPixel(originalData, i, j, col);
}
else
SetPixel(originalData, i, j, GetColor(originalData, i, 0));
Data[i, j] = c;
}
}
buffer.UnlockBits(originalData);
return buffer;
}
Now, I'm trying to think of a formula that will accept an angle and will out put an image where the solid lines are at the given angle.
For example, if I inputted 45 Degrees, the result would be:
Thank you for any help!
Here is the SetPixel code if that is needed:
private unsafe void SetPixel(BitmapData originalData, int x, int y, Color color)
{
//set the number of bytes per pixel
int pixelSize = 3;
//get the data from the original image
byte* oRow = (byte*)originalData.Scan0 + (y * originalData.Stride);
//set the new image's pixel to the grayscale version
oRow[x * pixelSize] = color.B; //B
oRow[x * pixelSize + 1] = color.G; //G
oRow[x * pixelSize + 2] = color.R; //R
}
This should be possible by using a rotated coordinate system. Transformation of i and j is as following:
x = i * cos(angle) - j * sin(angle);
y = j * cos(angle) + i * sin(angle);
Note: I'm not sure about degree/radians here, so adjust angle so it fits to the unit that cos and sin do need. Also, you might have to negate the angle depending on your desired rotation direction.
In fact, you only need x which replaces your use of i. We'll precompute sin(angle) and cos(angle) because these are quite costy operations we don't want in inner loops. Additionaly, your optimization is removed as we can't draw only one line and repeat it:
[...]
// double angle = ...
double cos_angle = cos(angle);
double sin_angle = sin(angle);
for (int i = 0; i < buffer.Width; i++)
{
for (int j = 0; j < buffer.Height; j++)
{
double val;
double x;
int c = 0;
x = i * cos_angle - j * sin_angle;
val = Math.Sin(inner * x);
val += 1;
val *= 128;
val = val > 255 ? 255 : val;
c = (int)val;
Color col = Color.FromArgb(c, c, c);
SetPixel(originalData, i, j, col);
Data[i, j] = c;
}
}
You can write a simple function rotate(x,y,angle) and use its result in SetPixel. You can google for rotation matrix.
A call with angle = 0, should produce default output.

Changing the tint of a bitmap while preserving the overall brightness

I'm trying to write a function that will let me red-shift or blue-shift a bitmap while preserving the overall brightness of the image. Basically, a fully red-shifted bitmap would have the same brightness as the original but be thoroughly red-tinted (i.e. the G and B values would be equal for all pixels). Same for blue-tinting (but with R and G equal). The degree of spectrum shifting needs to vary from 0 to 1.
Thanks in advance.
Here is the effect I was looking for (crappy JPEG, sorry):
alt text http://www.freeimagehosting.net/uploads/d15ff241ca.jpg
The image in the middle is the original, and the side images are fully red-shifted, partially red-shifted, partially blue-shifted and fully blue-shifted, respectively.
And here is the function that produces this effect:
public void RedBlueShift(Bitmap bmp, double factor)
{
byte R = 0;
byte G = 0;
byte B = 0;
byte Rmax = 0;
byte Gmax = 0;
byte Bmax = 0;
double avg = 0;
double normal = 0;
if (factor > 1)
{
factor = 1;
}
else if (factor < -1)
{
factor = -1;
}
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color color = bmp.GetPixel(x, y);
R = color.R;
G = color.G;
B = color.B;
avg = (double)(R + G + B) / 3;
normal = avg / 255.0; // to preserve overall intensity
if (factor < 0) // red-tinted:
{
if (normal < .5)
{
Rmax = (byte)((normal / .5) * 255);
Gmax = 0;
Bmax = 0;
}
else
{
Rmax = 255;
Gmax = (byte)(((normal - .5) * 2) * 255);
Bmax = Gmax;
}
R = (byte)((double)R - ((double)(R - Rmax) * -factor));
G = (byte)((double)G - ((double)(G - Gmax) * -factor));
B = (byte)((double)B - ((double)(B - Bmax) * -factor));
}
else if (factor > 0) // blue-tinted:
{
if (normal < .5)
{
Rmax = 0;
Gmax = 0;
Bmax = (byte)((normal / .5) * 255);
}
else
{
Rmax = (byte)(((normal - .5) * 2) * 255);
Gmax = Rmax;
Bmax = 255;
}
R = (byte)((double)R - ((double)(R - Rmax) * factor));
G = (byte)((double)G - ((double)(G - Gmax) * factor));
B = (byte)((double)B - ((double)(B - Bmax) * factor));
}
color = Color.FromArgb(R, G, B);
bmp.SetPixel(x, y, color);
}
}
}
You'd use the ColorMatrix class for this. There's a good tutorial available in this project.

Sharpen on a Bitmap using C#

I want to put a sharpen filter on an image. I have found a web with short tutorial.
I tried to do it in C# so here is my code. Anyway, I tried to find out why it is not working. I do not know if I am doing something wrong, if yes, please advise me what to do to make it work as it should be. Thanks
public static Bitmap sharpen(Bitmap image)
{
Bitmap sharpenImage = new Bitmap(image.Width, image.Height);
int filterWidth = 3;
int filterHeight = 3;
int w = image.Width;
int h = image.Height;
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
Color imageColor = image.GetPixel(x, y);
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + w) % w;
int imageY = (y - filterHeight / 2 + filterY + h) % h;
red += imageColor.R * filter[filterX, filterY];
green += imageColor.G * filter[filterX, filterY];
blue += imageColor.B * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
sharpenImage.SetPixel(i, j, result[i, j]);
}
}
return sharpenImage;
}
public static Bitmap sharpen(Bitmap image)
{
Bitmap sharpenImage = new Bitmap(image.Width, image.Height);
int filterWidth = 3;
int filterHeight = 3;
int w = image.Width;
int h = image.Height;
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
//=====[REMOVE LINES]========================================================
// Color must be read per filter entry, not per image pixel.
Color imageColor = image.GetPixel(x, y);
//===========================================================================
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + w) % w;
int imageY = (y - filterHeight / 2 + filterY + h) % h;
//=====[INSERT LINES]========================================================
// Get the color here - once per fiter entry and image pixel.
Color imageColor = image.GetPixel(imageX, imageY);
//===========================================================================
red += imageColor.R * filter[filterX, filterY];
green += imageColor.G * filter[filterX, filterY];
blue += imageColor.B * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
sharpenImage.SetPixel(i, j, result[i, j]);
}
}
return sharpenImage;
}
I took Daniel's answer and modified it for performance, by using BitmapData class, since using GetPixel/SetPixel is very expensive and inappropriate for performance-hungry systems. It works exactly the same as the previous solution and can be used instead.
public static Bitmap Sharpen(Bitmap image)
{
Bitmap sharpenImage = (Bitmap)image.Clone();
int filterWidth = 3;
int filterHeight = 3;
int width = image.Width;
int height = image.Height;
// Create sharpening filter.
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
// Lock image bits for read/write.
BitmapData pbits = sharpenImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// Declare an array to hold the bytes of the bitmap.
int bytes = pbits.Stride * height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(pbits.Scan0, rgbValues, 0, bytes);
int rgb;
// Fill the color array with the new sharpened color values.
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + width) % width;
int imageY = (y - filterHeight / 2 + filterY + height) % height;
rgb = imageY * pbits.Stride + 3 * imageX;
red += rgbValues[rgb + 2] * filter[filterX, filterY];
green += rgbValues[rgb + 1] * filter[filterX, filterY];
blue += rgbValues[rgb + 0] * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
// Update the image with the sharpened pixels.
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
rgb = y * pbits.Stride + 3 * x;
rgbValues[rgb + 2] = result[x, y].R;
rgbValues[rgb + 1] = result[x, y].G;
rgbValues[rgb + 0] = result[x, y].B;
}
}
// Copy the RGB values back to the bitmap.
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, pbits.Scan0, bytes);
// Release image bits.
sharpenImage.UnlockBits(pbits);
return sharpenImage;
}
This will create a softer sharpening effect. You can expand the filter array if you need to, or change the 16 to something larger, but I found this isn't as harsh as the one you have.
const int filterWidth = 5;
const int filterHeight = 5;
double[,] filter = new double[filterWidth,filterHeight] {
{ -1, -1, -1, -1, -1 },
{ -1, 2, 2, 2, -1 },
{ -1, 2, 16, 2, -1 },
{ -1, 2, 2, 2, -1 },
{ -1, -1, -1, -1, -1 }
};
double factor = 1.0 / 16.0;
I combined niaher's and David's answer and fixed the "bias" property. Now you can pass a "strength" between 0.0 and 1.0 to the Sharpen() function.
/// <summary>
/// Sharpens the specified image.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="strength">The strength between 0.0 and 1.0.</param>
/// <returns></returns>
public static Bitmap Sharpen(Image image, double strength)
{
using (var bitmap = image as Bitmap)
{
if (bitmap != null)
{
var sharpenImage = bitmap.Clone() as Bitmap;
int width = image.Width;
int height = image.Height;
// Create sharpening filter.
const int filterWidth = 5;
const int filterHeight = 5;
var filter = new double[,]
{
{-1, -1, -1, -1, -1},
{-1, 2, 2, 2, -1},
{-1, 2, 16, 2, -1},
{-1, 2, 2, 2, -1},
{-1, -1, -1, -1, -1}
};
double bias = 1.0 - strength;
double factor = strength/16.0;
var result = new Color[image.Width,image.Height];
// Lock image bits for read/write.
if (sharpenImage != null)
{
BitmapData pbits = sharpenImage.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
// Declare an array to hold the bytes of the bitmap.
int bytes = pbits.Stride*height;
var rgbValues = new byte[bytes];
// Copy the RGB values into the array.
Marshal.Copy(pbits.Scan0, rgbValues, 0, bytes);
int rgb;
// Fill the color array with the new sharpened color values.
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth/2 + filterX + width)%width;
int imageY = (y - filterHeight/2 + filterY + height)%height;
rgb = imageY*pbits.Stride + 3*imageX;
red += rgbValues[rgb + 2]*filter[filterX, filterY];
green += rgbValues[rgb + 1]*filter[filterX, filterY];
blue += rgbValues[rgb + 0]*filter[filterX, filterY];
}
rgb = y*pbits.Stride + 3*x;
int r = Math.Min(Math.Max((int) (factor*red + (bias*rgbValues[rgb + 2])), 0), 255);
int g = Math.Min(Math.Max((int) (factor*green + (bias*rgbValues[rgb + 1])), 0), 255);
int b = Math.Min(Math.Max((int) (factor*blue + (bias*rgbValues[rgb + 0])), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
// Update the image with the sharpened pixels.
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
rgb = y*pbits.Stride + 3*x;
rgbValues[rgb + 2] = result[x, y].R;
rgbValues[rgb + 1] = result[x, y].G;
rgbValues[rgb + 0] = result[x, y].B;
}
}
// Copy the RGB values back to the bitmap.
Marshal.Copy(rgbValues, 0, pbits.Scan0, bytes);
// Release image bits.
sharpenImage.UnlockBits(pbits);
}
return sharpenImage;
}
}
return null;
}
Ok, fixed the problem with distored edges. Here´s the updated one:
/// <summary>
/// Sharpens the specified image.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="strength">The strength.</param>
/// <returns></returns>
public static Bitmap Sharpen(Image image, double strength)
{
using (var bitmap = image as Bitmap)
{
if (bitmap != null)
{
var sharpenImage = bitmap.Clone() as Bitmap;
int width = image.Width;
int height = image.Height;
// Create sharpening filter.
const int filterSize = 5;
var filter = new double[,]
{
{-1, -1, -1, -1, -1},
{-1, 2, 2, 2, -1},
{-1, 2, 16, 2, -1},
{-1, 2, 2, 2, -1},
{-1, -1, -1, -1, -1}
};
double bias = 1.0 - strength;
double factor = strength/16.0;
const int s = filterSize/2;
var result = new Color[image.Width,image.Height];
// Lock image bits for read/write.
if (sharpenImage != null)
{
BitmapData pbits = sharpenImage.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
// Declare an array to hold the bytes of the bitmap.
int bytes = pbits.Stride*height;
var rgbValues = new byte[bytes];
// Copy the RGB values into the array.
Marshal.Copy(pbits.Scan0, rgbValues, 0, bytes);
int rgb;
// Fill the color array with the new sharpened color values.
for (int x = s; x < width - s; x++)
{
for (int y = s; y < height - s; y++)
{
double red = 0.0, green = 0.0, blue = 0.0;
for (int filterX = 0; filterX < filterSize; filterX++)
{
for (int filterY = 0; filterY < filterSize; filterY++)
{
int imageX = (x - s + filterX + width)%width;
int imageY = (y - s + filterY + height)%height;
rgb = imageY*pbits.Stride + 3*imageX;
red += rgbValues[rgb + 2]*filter[filterX, filterY];
green += rgbValues[rgb + 1]*filter[filterX, filterY];
blue += rgbValues[rgb + 0]*filter[filterX, filterY];
}
rgb = y * pbits.Stride + 3 * x;
int r = Math.Min(Math.Max((int)(factor * red + (bias * rgbValues[rgb + 2])), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + (bias * rgbValues[rgb + 1])), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + (bias * rgbValues[rgb + 0])), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
// Update the image with the sharpened pixels.
for (int x = s; x < width - s; x++)
{
for (int y = s; y < height - s; y++)
{
rgb = y*pbits.Stride + 3*x;
rgbValues[rgb + 2] = result[x, y].R;
rgbValues[rgb + 1] = result[x, y].G;
rgbValues[rgb + 0] = result[x, y].B;
}
}
// Copy the RGB values back to the bitmap.
Marshal.Copy(rgbValues, 0, pbits.Scan0, bytes);
// Release image bits.
sharpenImage.UnlockBits(pbits);
}
return sharpenImage;
}
}
return null;
}
hi i edit the code a litle bit and add two other matrices
for me this works now perfect
/// <summary>
/// Sharpens the specified image.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="strength">strength erwartet werte zwische 0 - 99</param>
/// <returns></returns>
public Bitmap Sharpen(Image image, whichMatrix welcheMatrix , double strength)
{
double FaktorKorrekturWert = 0;
//strenght muß für den jeweiligen filter angepasst werden
switch (welcheMatrix)
{
case whichMatrix.Gaussian3x3:
//diese Matrix benötigt einen strenght Wert von 0 bis -9.9 default ist -2.5
//und einen korekturwert von 16
strength = (strength * -1) / 10;
FaktorKorrekturWert = 16;
break;
case whichMatrix.Mean3x3:
//diese Matrix benötigt einen strenght Wert von 0 bis -9 default ist -2.25
//und einen Korrekturwert von 10
strength = strength * -9 / 100;
FaktorKorrekturWert = 10;
break;
case whichMatrix.Gaussian5x5Type1:
//diese Matrix benötigt einen strenght Wert von 0 bis 2.5 default ist 1.25
//und einen Korrekturwert von 12
strength = strength * 2.5 / 100;
FaktorKorrekturWert = 12;
break;
default:
break;
}
using (var bitmap = image as Bitmap)
{
if (bitmap != null)
{
var sharpenImage = bitmap.Clone() as Bitmap;
int width = image.Width;
int height = image.Height;
// Create sharpening filter.
var filter = Matrix(welcheMatrix);
//const int filterSize = 3; // wenn die Matrix 3 Zeilen und 3 Spalten besitzt dann 3 bei 4 = 4 usw.
int filterSize = filter.GetLength(0);
double bias = 1.0 - strength;
double factor = strength / FaktorKorrekturWert;
//const int s = filterSize / 2;
int s = filterSize / 2; // Filtersize ist keine Constante mehr darum wurde der befehl const entfernt
var result = new Color[image.Width, image.Height];
// Lock image bits for read/write.
if (sharpenImage != null)
{
BitmapData pbits = sharpenImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// Declare an array to hold the bytes of the bitmap.
int bytes = pbits.Stride * height;
var rgbValues = new byte[bytes];
// Copy the RGB values into the array.
Marshal.Copy(pbits.Scan0, rgbValues, 0, bytes);
int rgb;
// Fill the color array with the new sharpened color values.
for (int x = s; x < width - s; x++)
{
for (int y = s; y < height - s; y++)
{
double red = 0.0, green = 0.0, blue = 0.0;
for (int filterX = 0; filterX < filterSize; filterX++)
{
for (int filterY = 0; filterY < filterSize; filterY++)
{
int imageX = (x - s + filterX + width) % width;
int imageY = (y - s + filterY + height) % height;
rgb = imageY * pbits.Stride + 3 * imageX;
red += rgbValues[rgb + 2] * filter[filterX, filterY];
green += rgbValues[rgb + 1] * filter[filterX, filterY];
blue += rgbValues[rgb + 0] * filter[filterX, filterY];
}
rgb = y * pbits.Stride + 3 * x;
int r = Math.Min(Math.Max((int)(factor * red + (bias * rgbValues[rgb + 2])), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + (bias * rgbValues[rgb + 1])), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + (bias * rgbValues[rgb + 0])), 0), 255);
result[x, y] = System.Drawing.Color.FromArgb(r, g, b);
}
}
}
// Update the image with the sharpened pixels.
for (int x = s; x < width - s; x++)
{
for (int y = s; y < height - s; y++)
{
rgb = y * pbits.Stride + 3 * x;
rgbValues[rgb + 2] = result[x, y].R;
rgbValues[rgb + 1] = result[x, y].G;
rgbValues[rgb + 0] = result[x, y].B;
}
}
// Copy the RGB values back to the bitmap.
Marshal.Copy(rgbValues, 0, pbits.Scan0, bytes);
// Release image bits.
sharpenImage.UnlockBits(pbits);
}
return sharpenImage;
}
}
return null;
}
public enum whichMatrix
{
Gaussian3x3,
Mean3x3,
Gaussian5x5Type1
}
private double[,] Matrix(whichMatrix welcheMatrix)
{
double[,] selectedMatrix = null;
switch (welcheMatrix)
{
case whichMatrix.Gaussian3x3:
selectedMatrix = new double[,]
{
{ 1, 2, 1, },
{ 2, 4, 2, },
{ 1, 2, 1, },
};
break;
case whichMatrix.Gaussian5x5Type1:
selectedMatrix = new double[,]
{
{-1, -1, -1, -1, -1},
{-1, 2, 2, 2, -1},
{-1, 2, 16, 2, -1},
{-1, 2, -1, 2, -1},
{-1, -1, -1, -1, -1}
};
break;
case whichMatrix.Mean3x3:
selectedMatrix =new double[,]
{
{ 1, 1, 1, },
{ 1, 1, 1, },
{ 1, 1, 1, },
};
break;
}
return selectedMatrix;
}

Categories

Resources