BMP与IplImage相互转换

    技术2022-05-20  53

    下面的function 可以把 IplImage 转 Bitmap

       // - the IplImage "src" Image must have a IPL_DEPTH_8U depth              //   //   and 1 or 3 channels                                                  //   // - the convertion is done in regards to the ROI if it is set            //   // - if you want to stretch your TBitmap ,specify width and height before //   //   calling the function                                                 //      bool __fastcall TForm1::IplImageToTBitmap(const IplImage *src,Graphics::TBitmap *dest){       if (!src || !dest)           return false;       IplImage *temp;       CvRect roi;    if (src->roi)           roi=cvGetImageROI(src);       else          roi=cvRect(0,0,src->width,src->height);       temp=cvCreateImage(cvSize(roi.width,roi.height),IPL_DEPTH_8U,3);       if (src->nChannels!=3)           cvCvtColor(src,temp,CV_GRAY2RGB);       else          cvCopy(src,temp);       if (dest->Width==0 || dest->Height==0)       {           dest->Width = roi.width;           dest->Height = roi.height;       }       else      {           IplImage *temp1=cvCloneImage(temp);           cvReleaseImageData(temp);           cvInitImageHeader(temp,cvSize(dest->Width,dest->Height),IPL_DEPTH_8U,3,src->origin,4);        cvCreateImageData(temp);           roi.width=dest->Width;           roi.height=dest->Height;           cvResize(temp1,temp);           cvReleaseImage(&temp1);       }       dest->PixelFormat=pf24bit;       try {               unsigned char *pLine;           int x,y;           for(y=0 ;y<roi.height;y++)           {               pLine = (unsigned char *)dest->ScanLine[y];               for(x=0 ;x <roi.width*3  ;x++)               {                   pLine[x]= ((unsigned char*)(temp->imageData + temp->widthStep*y))[x];               }           }       }       catch(...)       {           ShowMessage("Error while converting ...");       }       cvReleaseImage(&temp);       return true;   }//-------------------------------------------------------------------

    下面的function 可以把 Bitmap 转 IplImage

    IplImage* hBitmap2Ipl(HBITMAP hBmp){     BITMAP bmp;     ::GetObject(hBmp,sizeof(BITMAP),&bmp);

         int nChannels = bmp.bmBitsPixel == 1 ? 1 : bmp.bmBitsPixel/8 ;     int depth = bmp.bmBitsPixel == 1 ? IPL_DEPTH_1U : IPL_DEPTH_8U;

         IplImage* img = cvCreateImageHeader( cvSize(bmp.bmWidth, bmp.bmHeight), depth, nChannels );     img->imageData = (char*)malloc(bmp.bmHeight*bmp.bmWidth*nChannels*sizeof(char));     memcpy(img->imageData,(char*)(bmp.bmBits),bmp.bmHeight*bmp.bmWidth*nChannels);

         return img;}


    最新回复(0)