opecv获取图像轮廓

获取轮廓

#import <opencv2/opencv.hpp>
#import <opencv2/imgcodecs/ios.h>
#import <opencv2/imgproc/types_c.h>

@implementation OpenCVHelper
+(UIImage *)getImageOutLine:(UIImage *)iputimg
{
    cv::Mat cvImage;
    UIImageToMat(iputimg, cvImage);
    cv::Mat gray;
    // Convert the image to grayscale;
    cv::cvtColor(cvImage, gray, CV_RGBA2GRAY);
    // Apply Gaussian filter to remove small edges
    cv::GaussianBlur(gray, gray, cv::Size(5,5), 1.2,1.2);
    // Calculate edges with Canny
    cv::Mat edges;
    cv::Canny(gray, edges, 0, 60);
    // Fill image with white color
    //cvImage.setTo(cv::Scalar(255,255,255,1));
    // Change color on edges
    // cvImage.setTo(cv::Scalar(0,128,255,255),edges);
    
    cv::Mat cvOutImage= cv::Mat::zeros(cvImage.size(), cvImage.type());
    cvOutImage.setTo(cv::Scalar(255,255,255,0));
    cvOutImage.setTo(cv::Scalar(0,139,139,1),edges);
    return MatToUIImage(cvOutImage);

}
@end

点阵操作:

-(UIImage *)transparentImage:(UIImage *)image
{
    
    // Create a pixel buffer in an easy to use format
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);
    
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);
    
    //alter the alpha
    int length = height * width * 4;
    for (int i=0; i<length; i+=4)
    {
        if (m_PixelBuf[i+0] ==255) {
            m_PixelBuf[i+0] =0;
            m_PixelBuf[i+1] =0;
            m_PixelBuf[i+2] =0;
            m_PixelBuf[i+3] =0;
        }
 
    }
    
    
    //create a new image
    CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    
    CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(ctx); 
    free(m_PixelBuf);
    
    UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
    CGImageRelease(newImgRef); 
    
    return finalImage;
}

  

posted @ 2015-01-23 12:12  Ethan_村长  阅读(729)  评论(0编辑  收藏  举报