如何将8位OpenCV IplImage*转换为32位IplImage*?

sgi*_*len 12 opencv iplimage bits-per-pixel bpp

我需要将8位IplImage转换为32位IplImage.使用来自整个网络的文档,我尝试了以下方法:

// general code
img2 = cvCreateImage(cvSize(img->width, img->height), 32, 3);
int height    = img->height;
int width     = img->width;
int channels  = img->nChannels;
int step1     = img->widthStep;
int step2     = img2->widthStep;
int depth1    = img->depth;
int depth2    = img2->depth;
uchar *data1   = (uchar *)img->imageData;
uchar *data2   = (uchar *)img2->imageData;

for(h=0;h<height;h++) for(w=0;w<width;w++) for(c=0;c<channels;c++) {
   // attempt code...
}

// attempt one
// result: white image, two red spots which appear in the original image too.
// this is the closest result, what's going wrong?!
// see: http://files.dazjorz.com/cache/conversion.png
((float*)data2+h*step2+w*channels+c)[0] = data1[h*step1+w*channels+c];

// attempt two
// when I change float to unsigned long in both previous examples, I get a black screen.

// attempt three
// result: seemingly random data to the top of the screen.
data2[h*step2+w*channels*3+c] = data1[h*step1+w*channels+c];
data2[h*step2+w*channels*3+c+1] = 0x00;
data2[h*step2+w*channels*3+c+2] = 0x00;

// and then some other things. Nothing did what I wanted. I couldn't get an output
// image which looked the same as the input image.
Run Code Online (Sandbox Code Playgroud)

如你所见,我真的不知道自己在做什么.我很想知道,但如果我能正确完成这项工作,我会更加喜欢它.谢谢你的帮助!

Mar*_*tin 29

您正在寻找的功能是cvConvertScale().它会自动为您进行任何类型转换.您只需要指定要缩放1/255(将范围[0 ... 255]映射到[0 ... 1]).

例:

IplImage *im8 = cvLoadImage(argv[1]);
IplImage *im32 = cvCreateImage(cvSize(im8->width, im8->height), 32, 3);

cvConvertScale(im8, im32, 1/255.);
Run Code Online (Sandbox Code Playgroud)

注意点1/255.- 强制进行双重划分.没有它你会得到0的标度.

  • 将double作为缩放因子传递是很重要的(这就是255后面有'.'的原因).1/255将评估为整数除法,并导致缩放因子为0.您的代码究竟与cvConvertScale()无关? (11认同)

Ste*_*idt 6

也许这个链接可以帮到你?

编辑响应OP和评论的第二次编辑

你有没有尝试过

float value = 0.5

代替

float value = 0x0000001;

我认为浮动颜色值的范围从0.0到1.0,其中1.0是白色.