Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iphone Converting IplImage to UIImage and back causes rotation

I am using some code to convert between iplimage and uiimage. I take a photo taken from the camera (a UIImage) and convert it to an iplimage and back using the code posted below. Unfortunately this causes the image to be rotated and stretched by 90 degrees. so if I take a 320x480 image it comes back a 320x480 image but the image has been rotated and rescaled so that it looks as if it were rotated 90 degrees (i.e a a 480x320 image) then scaled non-uniformly ... I cannot figure it out -- everything seems right (byte ordering etc.)

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

return iplimage;
}

+(UIImage *)UIImageFromIplImage:(IplImage *)image {
NSLog(@"IplImage (%d, %d) %d bits by %d channels, %d bytes/row %s", image->width, image->height, image->depth, image->nChannels, image->widthStep, image->channelSeq);

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, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault,
                                    provider, NULL, false, kCGRenderingIntentDefault);
UIImage *ret = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationRight];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return ret;
}
like image 293
user491880 Avatar asked Jan 21 '23 00:01

user491880


1 Answers

I had the same problem, too and I still didn't find out how to change the two methods so that they do not rotate the picture.

Instead I rotated the UIImage, e.g. my code looks like this:

//Change the rotation here

UIImage *imageCam= [UIImage imageWithCGImage:newImage scale:1.0 orientation:UIImageOrientationUp];

//Convert UIImage
IplImage *image = [self CreateIplImageFromUIImage:imageCam];
like image 190
wAroXxX Avatar answered Jan 31 '23 05:01

wAroXxX