简体   繁体   中英

Image conversion in OpenCV C#

Image<bgr,byte> WeightedImg;
.
.

double color;

for (int i = 0; i < dataArray.Length; i++){
    color = dataArray[i, 2];
    WeightedImg.Bitmap.SetPixel(x, y,Color.FromArgb((int)Math.Ceiling(color * R), (int)Math.Ceiling(color * G),(int)Math.Ceiling(color * B)));
}

this line:

WeightedImg.Bitmap.SetPixel(x, y,Color.FromArgb((int)Math.Ceiling(color * R),
   (int)Math.Ceiling(color * G),(int)Math.Ceiling(color * B)));

makes the program crash .. I want to set a pixel in a WeightedImg according to a double value .. Is that possible?

or Can I convert from Image<bgr,byte> to Bitmap or double[,] ?

Ok well your code works when I try it there are alternatives around this however.

This Code does work naturally providing colour*N < 255 (which produces a different error):

Image<Bgr, byte> img = new Image<Bgr,byte>(10,10);


double color = 5;
double R = 20, B = 20, G = 20;
img.Bitmap.SetPixel(0,0,Color.FromArgb((int)Math.Ceiling(color * R),(int)Math.Ceiling(color * G), (int)Math.Ceiling(color * B)));

Alternative way you could attempt the same operation are to assign the value directly note the Data property if memory serves me correct is [height,width,depth] format so:

img.Data[y,x, 0] = (byte)Math.Ceiling(color * R); //Red
img.Data[y,x, 1] = (byte)Math.Ceiling(color * G); //Green
img.Data[y,x, 2] = (byte)Math.Ceiling(color * B); //Blue

Or more directly you could use:

img[0, 0] = new Bgr(Color.FromArgb((int)Math.Ceiling(color * R), (int)Math.Ceiling(color * G), (int)Math.Ceiling(color * B)));

All of these methods work an I have been tested.

As for your other questions yes you can convert an image to a Bitmap

Bitmap x = img.ToBitmap();

You can't explicitly convert the data to a double [,,] (not double[,]) without reading through every pixel and taking the data from the image to this array which I wouldn't recommend alternatively the following formats are fine:

Image<Bgr,Double> img = new Image<Bgr,Double>(10,10); //or (filename) of course

and converting

Image<Bgr,Double> img_double = img.Convert<Bgr,Double>();

but remember you can't convert more than one item at a time a cannot be directly converted to it must be done like this:

Image<Gray,Double> img_gray = img.Convert<Gray,Byte>().Convert<Gray,Double>(); 
//or alternatively    
Image<Gray,Double> img_gray = img.Convert<Bgr,Double>().Convert<Gray,Double>(); 

If I had to guess, without knowing the exception, that you're Math.Ceiling calls are returning a value either less than 0 or greater than 255. Maybe limit the values prior to sending them to Color.FromArgb to that range. Also, double check that the x and y values are actually inside the image. It's difficult to tell considering the code above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM