OpenCV 2.4:C API实现cvMat转IplImage的技术咨询
First, let's walk through the correct ways to convert your CvMat (holding YUYV data) to IplImage—your initial attempt was on the right track, but we need to tweak it to fit your specific YUYV buffer scenario.
Shallow Copy (Efficient, No Data Duplication)
This method creates an IplImage header that points directly to your existing YUYV buffer, so no extra memory is used. Ideal if you don’t need to modify the original data independently:
// Your existing CvMat setup CvMat cvmat = cvMat(480, 640, CV_8UC2, yuyv_buff); // Create an IplImage header matching the CvMat's properties IplImage* yuyv_img = cvCreateImageHeader( cvSize(cvmat.cols, cvmat.rows), // Match width/height cvmat.depth(), // 8-bit depth for your YUYV data cvmat.channels() // 2 channels for YUYV format ); // Link the header to the CvMat's underlying buffer cvGetImage(&cvmat, yuyv_img);
Important note: When you’re done with this image, only release the header with cvReleaseImageHeader(&yuyv_img)—don’t use cvReleaseImage, as that would attempt to free your original yuyv_buff (which you likely own separately).
Deep Copy (Independent Data Buffer)
If you need the IplImage to have its own separate data (so changes to it don’t affect the original buffer), use one of these approaches:
// Option 1: Clone the shallow header to get a deep copy IplImage* yuyv_img_deep = cvCloneImage(yuyv_img); // Option 2: Create a new image and copy data directly IplImage* yuyv_img_deep = cvCreateImage( cvSize(cvmat.cols, cvmat.rows), cvmat.depth(), cvmat.channels() ); cvCopy(&cvmat, yuyv_img_deep);
For deep copies, release the full image with cvReleaseImage(&yuyv_img_deep) when finished.
Bonus: Color Conversion to BGR/RGB
Since you mentioned needing to perform color conversion, once you have the YUYV IplImage, you can convert it to a standard format like BGR:
// Create a 3-channel image for BGR output IplImage* bgr_img = cvCreateImage( cvSize(yuyv_img->width, yuyv_img->height), IPL_DEPTH_8U, 3 ); // Convert YUYV to BGR (use CV_YUY2RGB if you need RGB instead) cvCvtColor(yuyv_img, bgr_img, CV_YUY2BGR);
内容的提问来源于stack exchange,提问作者Avis

