Image conversion in OpenCV C#

本秂侑毒 提交于 2019-12-02 00:43:55

问题


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 doublevalue .. Is that possible?

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


回答1:


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>(); 



回答2:


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.



来源:https://stackoverflow.com/questions/7149510/image-conversion-in-opencv-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!