(Bitmap)image behaves differently than new Bitmap(image) - c#

Here is the test i wrote and that will currently fail:
var unusableColor = Color.FromArgb(13, 19, 20, 19);
var retrievedColor = Color.Empty;
var tempFile = Path.GetTempFileName();
using (var bitmap = new Bitmap(1, 1))
{
bitmap.SetPixel(0, 0, unusableColor);
bitmap.Save(tempFile, ImageFormat.Png);
}
using (var image = Image.FromFile(tempFile))
// This will lead to the error
using (var bitmap = new Bitmap(image))
// But this will work
//using (var bitmap = (Bitmap)image)
{
retrievedColor = bitmap.GetPixel(0, 0);
}
Assert.That(retrievedColor, Is.SameAs(unusableColor));
If you take a look into the retrievedColor you'll find that it will be the same as Color.FromArgb(13, 19, 19, 19). So the difference will be that the green part has changed from 20 to 19.
Any idea why this happens or under which circumstances the constructor of the Bitmap will change a pixel?
Update
Seems to be a deeper nested problem. By replacing the Bitmap constructor by a simple cast of the image variable the problem goes away. This maybe solves the problem, but it doesn't explain it. Further more i was able to reproduce the problem even in Paint.Net by the following procedure:
Open Paint.Net and create a new image (size doesn't matter)
Select all (Ctrl+A)
Remove the selection (Del)
Open the color dialog (F8)
Enter the above values for RGB (19, 20, 19) and at the bottom the transparency (13).
Select the fill tool (F)
Fill the color into the empty image
Select the color selection tool (K)
Click somewhere into your fresh image and watch the color dialog
So it seems it is maybe a deeper problem, not caused by the Bitmap or Image class but maybe by some deeper functionality like GDI+ or something similar.
Update 2
I just wrote a new test to find out all affected colors:
for (int a = 0; a < 256; a++)
{
for (int r = 0; r < 256; r++)
{
for (int g = 0; g < 256; g++)
{
for (int b = 0; b < 256; b++)
{
using (var bitmap = new Bitmap(1, 1))
{
var desiredColor = Color.FromArgb(a, r, g, b);
bitmap.SetPixel(0, 0, desiredColor);
// This will fail in a lot of colors with a low alpha channel value
using (var copiedBitmap = new Bitmap(bitmap))
// This will work, cause the information is entirely copied.
//using (var copiedBitmap = (Bitmap)bitmap.Clone())
{
var retrievedColor = copiedBitmap.GetPixel(0, 0);
if (desiredColor != retrievedColor)
{
Debug.Print(desiredColor + " != " + retrievedColor);
}
}
}
}
}
}
Please don't let it run completely on itself, cause it will take a loonng time to finish and it also finds a looots of differences. But what you can see, if you play around with the transparency (setting to 1 or 10) then you'll see that the RGB values use this as some kind of bit depth.
So the problem occurs if you create a new Bitmap from an existing one that uses low transparency values. The real root cause seems to be far down in GDI, Kernel or somewhere in this area and can't be solved from .Net.
Simply be aware that a color can change by calling the bitmap constructor if the color has a low transparency value. If you really need the original colors to stay alive in a second instance instead use (Bitmap)myBitmap.Clone() or if you load it from disk use (Bitmap)Image.FromFile(filename) cause Image is only an abstract class which will normally instantiated through the Bitmap class.

I checked PNG file saved with your code using Paint.NET and pixel color is exactly unusableColor.
If you change your reading code with this:
using (Bitmap bitmap = (Bitmap)Image.FromFile(tempFile))
{
retrievedColor = bitmap.GetPixel(0, 0);
}
everything works

you can use Clone method:
using (var image = Image.FromFile(tempFile))
{
using (var bitmap = image.Clone() as Bitmap)
{
retrievedColor = bitmap.GetPixel(0, 0);
}
}
Problem is in 'new Bitmap(image)' because it creates new instance. If you look into bitmap's constructor, it creates new transparent image and draws source image. graphics object has smoothing mode property, which is used for drawing quality. default is no antialiasing.
Here is the Bitmap's constructor:
Graphics graphics = null;
try
{
graphics = Graphics.FromImage(this);
graphics.Clear(Color.Transparent);
graphics.DrawImage(original, 0, 0, width, height);
}
finally
{
if (graphics != null)
{
graphics.Dispose();
}
}
So if you just load image from file, or clone, bitmap data is same.

Related

Concatenate a bitmap (rgb) with a TIFF (cmyk) without converting cmyk to rgb

I'm developing an application to concatenate a bitmap image in RGB with a TIFF in CMYK.
I've tried with System.Drawing and System.Windows.Media namespaces.
The problem is both the libraries try to convert my TIFF image into RGB before merging, which causes a loss in image quality.
As far as I understand, the reason they always convert images into RGB before processing because the two libraries do that with a rendering intent.
I don't need to render anything, just merge the two photos and save to disk, that's all.
What should I do to achieve my goal? Clearly, I don't want to lose the quality of the TIFF so I think it's best to not do any conversion, just keep it raw and merge. Anyway, that's just a guess, other option could be considered as well. Could anybody shed some light on my case please?
See a comparison of the tiff image before and after converted from cmyk to rgb below.
I’m not aware of any capacity in the TIFF format to have two different color spaces at the same time. Since you are dealing in CMYK, I assume that is the one you want to preserve.
If so, the steps to do so would be:
Load CMYK image A (using BitmapDecoder)
Load RGB image B (using BitmapDecoder)
Convert image B to CMYK with the desired color profile (using FormatConvertedBitmap)
If required, ensure the pixel format for image B matches A (using FormatConvertedBitmap)
Composite the two in memory as a byte array (using CopyPixels, then memory manipulation, then new bitmap from the memory)
Save the composite to a new CMYK TIFF file (using TiffBitmapEncoder)
That should be possible with WIC (System.Media).
An example doing so (github) could be written as:
BitmapFrame LoadTiff(string filename)
{
using (var rs = File.OpenRead(filename))
{
return BitmapDecoder.Create(rs, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad).Frames[0];
}
}
// Load, validate A
var imageA = LoadTiff("CMYK.tif");
if (imageA.Format != PixelFormats.Cmyk32)
{
throw new InvalidOperationException("imageA is not CMYK");
}
// Load, validate, convert B
var imageB = LoadTiff("RGB.tif");
if (imageB.PixelHeight != imageA.PixelHeight)
{
throw new InvalidOperationException("Image B is not the same height as image A");
}
var imageBCmyk = new FormatConvertedBitmap(imageB, imageA.Format, null, 0d);
// Merge
int width = imageA.PixelWidth + imageB.PixelWidth,
height = imageA.PixelHeight,
bytesPerPixel = imageA.Format.BitsPerPixel / 8,
stride = width * bytesPerPixel;
var buffer = new byte[stride * height];
imageA.CopyPixels(buffer, stride, 0);
imageBCmyk.CopyPixels(buffer, stride, imageA.PixelWidth * bytesPerPixel);
var result = BitmapSource.Create(width, height, imageA.DpiX, imageA.DpiY, imageA.Format, null, buffer, stride);
// save to new file
using (var ws = File.Create("out.tif"))
{
var tiffEncoder = new TiffBitmapEncoder();
tiffEncoder.Frames.Add(BitmapFrame.Create(result));
tiffEncoder.Save(ws);
}
Which maintains color accuracy of the CMYK image, and converts the RGB using the system color profile. This can be verified in Photoshop which shows that the each letter, and rich black, have maintained their original values. (note that imgur does convert to png with dubious color handling - check github for originals.)
Image A (CMYK):
Image B (RGB):
Result (CMYK):
To have the two images overlayed, one image would have to have some notion of transparency. A mask would be one example thereof, where you pick a particular color value to mean "transparent". The downside of a mask is that masks do not play well with aliased source images. For that, you would want to do an alpha channel - but blending across color spaces would be challenging. (Github)
// Load, validate A
var imageA = LoadTiff("CMYK.tif");
if (imageA.Format != PixelFormats.Cmyk32)
{
throw new InvalidOperationException("imageA is not CMYK");
}
// Load, validate, convert B
var imageB = LoadTiff("RGBOverlay.tif");
if (imageB.PixelHeight != imageA.PixelHeight
|| imageB.PixelWidth != imageA.PixelWidth)
{
throw new InvalidOperationException("Image B is not the same size as image A");
}
var imageBBGRA = new FormatConvertedBitmap(imageB, PixelFormats.Bgra32, null, 0d);
var imageBCmyk = new FormatConvertedBitmap(imageB, imageA.Format, null, 0d);
// Merge
int width = imageA.PixelWidth, height = imageA.PixelHeight;
var stride = width * (imageA.Format.BitsPerPixel / 8);
var bufferA = new uint[width * height];
var bufferB = new uint[width * height];
var maskBuffer = new uint[width * height];
imageA.CopyPixels(bufferA, stride, 0);
imageBBGRA.CopyPixels(maskBuffer, stride, 0);
imageBCmyk.CopyPixels(bufferB, stride, 0);
for (int i = 0; i < bufferA.Length; i++)
{
// set pixel in bufferA to the value from bufferB if mask is not white
if (maskBuffer[i] != 0xffffffff)
{
bufferA[i] = bufferB[i];
}
}
var result = BitmapSource.Create(width, height, imageA.DpiX, imageA.DpiY, imageA.Format, null, bufferA, stride);
// save to new file
using (var ws = File.Create("out_overlay.tif"))
{
var tiffEncoder = new TiffBitmapEncoder();
tiffEncoder.Frames.Add(BitmapFrame.Create(result));
tiffEncoder.Save(ws);
}
Example image B:
Example output:

How can I remove transparency from an animated GIF?

I can't believe this hasn't been asked yet, but...
How can I replace the transparent background of a GIF image to white, without breaking the animation?
I am way out of my field here, so I'm pretty much lost (I really don't know what to do).
This is what I tried without luck:
public byte[] RemoveTransparency(byte[] gifBytes)
{
using(MemoryStream gifStream = new MemoryStream(gifBytes))
using(Image gifImage = Image.FromStream(gifStream))
using(Image newImage = new Bitmap(gifImage.Width, gifImage.Height, PixelFormat.Format32bppPArgb))
using(MemoryStream newImageStream = new MemoryStream())
{
Color background = Color.White;
newImage.SetResolution(gifImage.HorizontalResolution, gifImage.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(newImage))
{
graphics.Clear(background );
graphics.DrawImage(gifImage, 0, 0, gifImage.Width, gifImage.Height);
}
newImage.Save(newImageStream);
return newImageStream.ToArray();
}
}
You can use a bitmap.
using(var ms = new MemoryStream(gifBytes))
using(var b = new Bitmap(Image.FromStream(ms)))
{
for(var y = 0; y < b.Height; ++y)
for(var x = 0; x < b.Width; ++x)
if(b.GetPixel(x, y).A == 0) //Completely opaque
b.SetPixel(x, y, Color.White); //Sets white
}
//Note: b goes out of scope here and will be deleted eventually.
Do note that this algorithm is extremely slow on large images, a typical approach to get around this is to access the internal buffer directly which requires unsafe context. See MSDN Bitmap reference or this: https://msdn.microsoft.com/en-us/library/5ey6h79d(v=vs.110).aspx
If the bitmap breaks the animation, load each frame as described in the comments of your post and then write the final buffer back into main image memory. Comment if you want me to edit for this context.

Error saving resized image

I have the following code
int oswidth = 0;
int osheight = 0;
if (comboBox3.SelectedIndex == 0)
{
oswidth = Convert.ToInt32(textBox5.Text.ToString());
osheight = Convert.ToInt32(textBox6.Text.ToString());
}
else if (comboBox3.SelectedIndex == 1)
{
oswidth = 38 * Convert.ToInt32(textBox5.Text.ToString());
osheight = 38 * Convert.ToInt32(textBox6.Text.ToString());
}
Bitmap oldimg = new Bitmap(pictureBox3.Image);
Bitmap objBitmap = new Bitmap(oldimg, new Size(oswidth, osheight));
objBitmap.Save(pictureBox3.ImageLocation.ToString(), ImageFormat.Jpeg);
The problem is when the selected index is 0 it works fine
but when the selected index is 1 i get a error "Parameter is not valid."
i tried different images but same error. is it the multiply by 32 thing
The Parameter is not valid error message when trying to create a Bitmap usually means that you are trying to allocate too much memory to it. The bitmap requires bit-depth*width*height/8 bytes of contiguous memory, and there just isn't enough available to satisfy that.
In this case, it looks like it's because you're multiplying its dimensions by 38 (and therefore multiplying the size in memory by 38^2).
You could utilize the following method:
private static void ResizeImage(string file, double vscale, double hscale, string output)
{
using(var source = Image.FromFile(file))
{
var width = (int)(source.Width * vscale);
var height = (int)(source.Height * hscale);
using(var image = new Bitmap(width, height, PixelFormat.Format24bppRgb))
using(var graphic = Graphics.FromImage(image))
{
graphic.SmoothingMode = SmoothingMode.AntiAlias;
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.DrawImage(source, new Rectangle(0, 0, width, height));
image.Save(output);
}
}
}
You can tailor this however you'd like, but it should meet your needs.
Important: The reason vscale and hscale are separate is to not follow scaling. You can easily combine them so you can scale accordingly. The other thing to remember, is your using a value of 32. Try using a value of .32 which will treat it more like a percent, which will scale. Also it won't increase the memory drastically causing your error.

Cannot draw an image using this program?

I am trying to process an image for finding out red color regions in it. I scan pixels and if they are found to be ENOUGH red, they are converted to black, otherwise white.
To speed up the process, I skip certain pixels, and need to draw blocks of black or white at their place. I am using this function but it seems to be wrong somewhere. The image I get in the end is completely blank.
public void ProcessFrame( ref Bitmap image )
{
int skip = 10;
Graphics g = Graphics.FromImage(System.Drawing.Image.FromHbitmap(image.GetHbitmap()));
SolidBrush black = new SolidBrush(Color.Black);
SolidBrush white = new SolidBrush(Color.White);
for (int i = 0; i < image.Width; i=i+skip)
{
for (int j = 0; j < image.Height; j = j + skip)
{
Color cl = image.GetPixel(i, j);
if (cl.R > (cl.G * 2) && cl.R > (cl.B * 2))
{
g.FillRectangle(black, new Rectangle(i, j, skip, skip));
}
else
{
g.FillRectangle(white, new Rectangle(i, j, skip, skip));
}
}
}
}
Can you point out the mistake, OR any other better method to achieve what I aim for?
By blank, do you mean white?
I don't know your image, but if (cl.R > (cl.G * 2) && cl.R > (cl.B * 2)) is not a good test for redness. #010000 passes that test, but is basically black. And, #ffaaaa looks red, but won't pass.
If you had a very dark image, lots of pixels might pass that test that aren't very red. With a light image, lots of red pixels won't pass.
Probably the best way is to convert the color the HSL, and then use values of H(ue) that are in the red zone, but only if S(aturation) and L(uminance) are sufficiently bright and non-gray (over a threshhold to not just be black or gray).
Try to use:
Graphics g = Graphics.FromImage(image);
Then consider other replies to improve your color testing.
You didn't show where image is created, but this code will draw into a bitmap:
var bmp = new Bitmap(200,200);
using (g = Graphics.FromImage(bmp))
{
g.FillEllipse(Brushes.Red, 10, 10, 50, 50);
}
Note that you need to call Graphics.Dispose (or use using) before using the image.
Also note that using GetPixel for image processing will be very slow. Use low-level memory access (Bitmap.LockBits) or try some image processing library for .NET (like AForge).

Fill the holes in emgu cv

How can I fill the holes in binary image in emgu cv?
In Aforge.net it's easy, use Fillholes class.
Thought the question is a little bit old, I'd like to contribute an alternative solution to the problem.
You can obtain the same result as Chris' without memory problem if you use the following:
private Image<Gray,byte> FillHoles(Image<Gray,byte> image)
{
var resultImage = image.CopyBlank();
Gray gray = new Gray(255);
using (var mem = new MemStorage())
{
for (var contour = image.FindContours(
CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
RETR_TYPE.CV_RETR_CCOMP,
mem); contour!= null; contour = contour.HNext)
{
resultImage.Draw(contour, gray, -1);
}
}
return resultImage;
}
The good thing about the method above is that you can selectively fill holes that meets your criteria. For example, you may want to fill holes whose pixel count (count of black pixels inside the blob) is below 50, etc.
private Image<Gray,byte> FillHoles(Image<Gray,byte> image, int minArea, int maxArea)
{
var resultImage = image.CopyBlank();
Gray gray = new Gray(255);
using (var mem = new MemStorage())
{
for (var contour = image.FindContours(
CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE,
RETR_TYPE.CV_RETR_CCOMP,
mem); contour!= null; contour = contour.HNext)
{
if ( (contour.Area < maxArea) && (contour.Area > minArea) )
resultImage.Draw(contour, gray, -1);
}
}
return resultImage;
}
Yes there is a method but it's a bit messy as its based on cvFloodFill operation. Now all this algorithm is designed to do is fill an area with a colour until it reaches an edge similar to a region growing algorithm. To use this effectively you need to use a little inventive coding but I warn you this code is only to get you started it may require re-factoring to speed things up . As it stands the loop goes through each of your pixels that are less then 255 applies cvFloodFill checks what size the area is and then if it is under a certain area fill it in.
It is important to note that a copy of the image is made of the original image to be supplied to the cvFloodFill operation as a pointer is used. If the direct image is supplied then you will end up with a white image.
OpenFileDialog OpenFile = new OpenFileDialog();
if (OpenFileDialog.ShowDialog() == DialogResult.OK)
{
Image<Bgr, byte> image = new Image<Bgr, byte>(OpenFile.FileName);
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
if (image.Data[j, i, 0] != 255)
{
Image<Bgr, byte> image_copy = image.Copy();
Image<Gray, byte> mask = new Image<Gray, byte>(image.Width + 2, image.Height + 2);
MCvConnectedComp comp = new MCvConnectedComp();
Point point1 = new Point(i, j);
//CvInvoke.cvFloodFill(
CvInvoke.cvFloodFill(image_copy.Ptr, point1, new MCvScalar(255, 255, 255, 255),
new MCvScalar(0, 0, 0),
new MCvScalar(0, 0, 0), out comp,
Emgu.CV.CvEnum.CONNECTIVITY.EIGHT_CONNECTED,
Emgu.CV.CvEnum.FLOODFILL_FLAG.DEFAULT, mask.Ptr);
if (comp.area < 10000)
{
image = image_copy.Copy();
}
}
}
}
}
The "new MCvScalar(0, 0, 0), new MCvScalar(0, 0, 0)," are not really important in this case as you are only filling in results of a binary image. YOu could play around with other settings to see what results you can achieve. "if (comp.area < 10000)" is the key constant to change is you want to change what size hole the method will fill.
These are the results that you can expect:
Original
Results
The problem with this method is it's extremely memory intensive and it managed to eat up 6GB of ram on a 200x200 image and when I tried 200x300 it ate all 8GB of my RAM and brought everything to a crashing halt. Unless a majority of your image is white and you want to fill in tiny gaps or you can minimise where you apply the method I would avoid it. I would suggest writing you own class to examine each pixel that is not 255 and add the number of pixels surrounding it. You can then record the position of each pixel that was not 255 (in a simple list) and if your count was bellow a threshold set these positions to 255 in your images (by iterating though the list).
I would stick with the Aforge FillHoles class if you do not wish to write your own as it is designed for this purpose.
Cheers
Chris
you can use FillConvexPoly
image.FillConvexPoly(externalContours.ToArray(), new Gray(255));

Categories

Resources