美文网首页
iOS-OpenCV对比度增强(矩阵掩码操作)

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

作者: 沙琪玛dd | 来源:发表于2016-11-02 21:18 被阅读223次

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

  • I(i,j) = 5*I(i,j) - [I(i-1,j) -I(i+1,j) - I(i,j-1) - I(i,j+1)];

  • 矩阵掩码的设置为
    0 -1 0
    (-1 5 -1)
    0 -1 0

  • 首先使用基本的像素访问方法来实现对比度增强函数,然后我们再用opencv库中的filter2D函数来实现相同的效果,通过计算调用的时间来对比两种方法的优劣性。

  • 基本方法

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));
    }
}
  • filter2D函数方法
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);
        
}
  • 基本方法花费时间0.0142秒,filter2D方法花费时间0.0057秒
sharpen.png sharpenx.png
  • 可以得出filter2D的方法要比自己实现的方法要快
    最后是效果图展示:
test1.png

相关文章

网友评论

      本文标题:iOS-OpenCV对比度增强(矩阵掩码操作)

      本文链接:https://www.haomeiwen.com/subject/zoqbuttx.html