002图像矩阵掩膜操作

矩阵掩膜操作

  1. 获取图像像素指针:

    • Mat.ptr<uchar>(int i=0) 获取像素矩阵的指针,索引i表示第几行,从0开始计行数。

    • 获得当前行指针const uchar* current= myImage.ptr<uchar>(row );

    • 获取当前像素点P(row, col)的像素值 p(row, col) =current[col]

       

  2. 像素范围处理saturate_cast<uchar>

    • saturate_cast<uchar>(-100),返回 0

    • saturate_cast<uchar>(288),返回255

    • saturate_cast<uchar>(100),返回100

    • 这个函数的功能是确保RGB值得范围在0~255之间

       

  3. 掩膜操作(提高图像对比度):

     

 

 

 

  • 1.定义掩膜:Mat kernel = (Mat_<char>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);

  • filter2D( src, dst, src.depth(), kernel );其中src与dst是Mat类型变量、src.depth表示位图深度,有32、24、8等

#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>

using namespace cv;

int main002(int argc,char** argv) {
    Mat src, dst;
    //读取图像
    src = imread("C:/Users/aber/Desktop/data/baboon.jpg");
    //判断图像是否加载成功
    if (!src.data)
    {
        printf("could not load image....\n");
        return -1;
    }
    //创建窗口
    namedWindow("input image", 1);
    //显示图像
    imshow("input image", src);

    //int cols = (src.cols - 1) * src.channels();//宽度
    //int offsetx = src.channels();
    //int rows = src.rows;//高度

    ////初始化dst
    //dst = Mat::zeros(src.size(), src.type());
    //for (int row = 1; row < (rows - 1); row++) {
    //    //上一行
    //    const uchar* previous = src.ptr<uchar>(row - 1);
    //    //当前行指针
    //    const uchar* current = src.ptr<uchar>(row);
    //    //下一行
    //    const uchar* next = dst.ptr<uchar>(row);
    //    uchar* output = dst.ptr<uchar>(row);
    //    for (int col = offsetx; col < cols; col++)
    //    {
    //        //saturate_cast函数确保数值在0~255之间
    //        output[col] = saturate_cast<uchar>(5 * current[col] - (current[col - offsetx] + current[col + offsetx] + previous[col] + next[col]));

    //    }
    //}

    double t = getTickCount();
    //定义掩膜操作数
    Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    //调用filter2D函数执行掩膜操作
    filter2D(src, dst, src.depth(), kernel);
    //执行时间
    double timeconsume = (getTickCount() - t) / getTickFrequency();
    printf("time consume %.2f\n", timeconsume);

    namedWindow("constrast image demo", 1);
    imshow("constract image demo", dst);

    //让图像显示等待手动关闭
    waitKey(0);
    return 0;
}

 

 

 

posted @ 2021-06-03 20:00  阿尔飞  阅读(76)  评论(0)    收藏  举报