Click here to Skip to main content
16,020,080 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a grayscale 30x40 image and I want to get its equivalent binary format and later multiply it with a 40x1 matrix so that I would be able to sort of compress it. This is the code which allows me to convert to binary, how can put in a matrix and multiply it?

C#
private byte[] toBin(Bitmap b)
        {
                byte[] binVals = new byte[imgSize];
                int k = 0;
                for (int i = 0; i < img.Height; i ++)
                {
                    for (int j = 0; j < img.Width; j ++)
                    {
                        if (img.GetPixel(j, i).A.ToString() == "255" && img.GetPixel(j, i).B.ToString() == "255")
                        {
                            byte z = (byte)0;
                            binVals[k] = z;
                            k++;
                        }
                        else
                        {
                            byte z = (byte)1;
                            binVals[k] = z;
                            k++;
                        }
                    }
                }

                return (binVals);
        }
Posted
Comments
E.F. Nijboer 29-Nov-12 11:07am    
You might want to change: img.GetPixel(j, i).A.ToString() == "255"
into this: img.GetPixel(j, i).A == 255
Matt T Heffron 29-Nov-12 20:42pm    
This appears to be doing a grayscale to black/white conversion with a *very* extreme threshold.
(I don't know your application, but in general, I'd have expected the split to be at the half-intensity value of 128, or the midpoint between the max and min intensity of the input image.)

Why are you putting this into a 1-dimensional array, instead of one the same shape as your input?
The 1-dimensional representation will make the matrix multiplication implementation much more difficult.

1 solution

You are going nowhere, in terms of performance, which would be killed by your GetPixel/PutPixel. You need to use System.Drawing.Bitmap.LockBits instead:
http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.lockbits.aspx[^].

There is a short and clear code sample on the help page on the first of the methods referenced.

I don't know what's your problem with matrix multiplication; this operation is very simple.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900