2011-06-04 138 views
1

我想將灰度iplimage轉換爲uiimage和viceversa。我有兩種方法可以在RGB色彩空間轉換中獲得成功,但對灰色圖像沒有成功。灰色UIImage - 灰色IP圖像轉換

- (UIImage *)UIImageFromIplImage:(IplImage *)image { 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
NSData *data = [NSData dataWithBytes:image->imageData length:image->imageSize]; 
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data); 
CGImageRef imageRef = CGImageCreate(image->width, image->height, 
            image->depth, image->depth * image->nChannels, image->widthStep, 
            colorSpace, kCGImageAlphaNone|kCGBitmapByteOrderDefault, 
            provider, NULL, false, kCGRenderingIntentDefault); 
UIImage *ret = [UIImage imageWithCGImage:imageRef]; 

CGImageRelease(imageRef); 

CGDataProviderRelease(provider); 
CGColorSpaceRelease(colorSpace); 
return ret; 

}

- (IplImage *)CreateIplImageFromUIImage:(UIImage *)image { 

CGImageRef imageRef = image.CGImage; 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4); 
CGContextRef contextRef = CGBitmapContextCreate(iplimage->imageData, iplimage->width, iplimage->height, 
               iplimage->depth, iplimage->widthStep, 
               colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault); 
CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef); 

CGContextRelease(contextRef); 
CGColorSpaceRelease(colorSpace); 

IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 3); 
cvCvtColor(iplimage, ret, CV_RGBA2BGR); 
cvReleaseImage(&iplimage); 

return ret; 

}

我需要幫助在這一點上找出我的問題。

在此先感謝..

+0

當您嘗試使用灰度圖像時,什麼不起作用? – damian 2011-06-13 09:44:23

回答

1

在傳遞參數之前轉換顏色通道怎麼樣?

IplImage *image = cvCreateImage(cvGetSize(imgGray), IPL_DEPTH_32F, 3); 
    cvCvtColor(imgGray, image, CV_GRAY2BGR); 
    imageView.image = [self UIImageFromIplImage:image];