Opencv(C++)笔记--掩码操作

1--原理

        使用以下掩码矩阵对图像进行处理:

0

-1

0

-1

5

-1

0

-1

0

        Opencv彩色图像在内存中的存储方式:

col0

col1

row0

B

G

R

B

G

R

row1

B

G

R

B

G

R

row2

B

G

R

B

G

R

2--代码

# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;

int main(int argc, char** argv){
    Mat src, dst;
    src = imread("./test1.jpg");
    if (!src.data){
        printf("could not load image..\n");
        return -1;
    }

    int cols = (src.cols - 1) * src.channels();
    int offsetx = src.channels();
    // printf("offsetx is : %d", src.channels());
    int rows = src.rows;
    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 = src.ptr<uchar>(row + 1);
        uchar* output = dst.ptr<uchar>(row); 
        
        for (int col = offsetx; col < cols; col++){
            output[col] = saturate_cast<uchar>(5 * current[col] - (current[col - offsetx] + current[col + offsetx] + previous[col] + next[col])); 
        }
    }
    
    namedWindow("input");
    imshow("input", src);
    namedWindow("output");
    imshow("output", dst);
    waitKey(0);
    return 0;
}

3--Opencv函数filter2D

# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;

int main(int argc, char** argv){
    Mat src, dst;
    src = imread("./test1.jpg");
    if (!src.data){
        printf("could not load image..\n");
        return -1;
    }

    Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    filter2D(src, dst, src.depth(), kernel);

    namedWindow("input");
    imshow("input", src);
    namedWindow("output");
    imshow("output", dst);
    waitKey(0);
    return 0;
}

4--知识点

① filter2D函数:实质上是一个过滤器,通过一个kernel矩阵对图像进行滤波操作,其用法如下图所示:filter2D(src, dst, ddepth, kernel, anchor=None, delta=None, borderType=None)

比较重要的参数:src 表示源图像,dst 表示生成的目标图像,ddepth 表示目标图像的深度,默认为与源图像相同,kernel 为自定义的滤波矩阵;

② saturate_cast<uchar>的用法:将像素值约束在0-255之间,当像素值小于0时置0,当像素值大于255时置255;

③ 通过指针遍历图片像素的方法:需要注意彩色图像在内存中的存储方式,B、G、R三种颜色是依次存储在内存中的(见图2);

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值