iOS-OpenCV对比度增强(矩阵掩码操作)

2016-11-02  本文已影响223人  沙琪玛dd

在本章通过矩阵的掩码操作重新计算图像中每个像素的值,掩码矩阵中的值表示邻近像素的值对新的像素值有多大的影响。我们利用以下的公式来实现增强对比度的效果。

void Sharpen (const Mat& myPicture,Mat& resultPicture)
{
    CV_Assert(myPicture.depth() == CV_8U);
    resultPicture.create(myPicture.size(), myPicture.type());
    const int myChannels = myPicture.channels();
    for(int i  = 1;i < myPicture.rows - 1; ++ i)
    {
        const uchar* previous = myPicture.ptr<uchar>(i - 1);
        const uchar* current = myPicture.ptr<uchar>(i);
        const uchar* next = myPicture.ptr<uchar>(i+1);
        uchar* output = resultPicture.ptr<uchar>(i);
        
        for(int j = myChannels; j < (myPicture.cols - 1)*myChannels; ++ j)
        {
            *output++ = saturate_cast<uchar>(5*current[j] - current[j - myChannels] - current[j + myChannels] - previous[j] - next[j]);
        }
        
        resultPicture.row(0).setTo(Scalar(0));
        resultPicture.row(resultPicture.rows-1).setTo(Scalar(0));
        resultPicture.col(0).setTo(Scalar(0));
        resultPicture.col(resultPicture.cols-1).setTo(Scalar(0));
    }
}
void Sharpenx (const Mat& myPicture , Mat& resultPicture)
{
    Mat kern = (Mat_<char>(3,3) << 0, -1 , 0 ,
                                   -1, 5 ,-1 ,
                                    0, -1, 0);
    filter2D(myPicture,resultPicture, myPicture.depth(), kern);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect rect = [UIScreen mainScreen].bounds;
    self.imgView.frame = rect;
    
    UIImage *image = [UIImage imageNamed:@"test.jpg"];
    UIImageToMat(image, myPictureMat);
    
    double t = (double)getTickCount();//得到某段时间以来CPU走过的时钟周期数
    Sharpenx(myPictureMat, resultPictureMat);
    
    t = ((double)getTickCount() - t)/getTickFrequency();//getTickFrequency()函数返回CPU1s中所走的时钟周期数
    cout<< "--------------cost:" << t <<" seconds-----------------" <<endl;
    
    self.imgView.image = MatToUIImage(resultPictureMat);
        
}
sharpen.png sharpenx.png test1.png
上一篇下一篇

猜你喜欢

热点阅读