ios--OpenCV--图像像素颜色反转


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImage *mImage =  [UIImage imageNamed:@"防伪标签001.jpg"];
    self.imageView.image = mImage;
    
    IplImage *image = [self convertToIplImage:mImage];
    CvScalar cs;
    for (int i=0; i< image->height; i++) {
        for (int j=0; j < image->width; j++) {
            cs = cvGet2D(image, i, j);
            cs.val[0] = 255 - cs.val[0];
            cs.val[1] = 255 - cs.val[1];
            cs.val[2] = 255 - cs.val[2];
           cvSet2D(image,i, j, cs);
            printf("cs.val[0]=%f,val[1]=%f,val[2]=%f/n",cs.val[0],cs.val[1],cs.val[2]);
        }
    }
    
    self.imageView1.image = [self convertToUIImage:image];
}


/// UIImage类型转换为IPlImage类型
-(IplImage*)convertToIplImage:(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_RGB2BGR);
    cvReleaseImage(&iplImage);
    return ret;
}

/// IplImage类型转换为UIImage类型
-(UIImage*)convertToUIImage:(IplImage*)image
{
    cvCvtColor(image, image, CV_BGR2RGB);
    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;
}


你可能感兴趣的:(ios开发,图像处理OpenCV)