/*
矩阵的掩膜操作 0 掩膜mask 在这里进行增强对比度:
[
[ 0,-1, 0 ],
[-1, 5, -1],
[ 0,-1, 0 ]
]
使用mask滑动图片每一个位置,进行卷积运算
这里这个mask会增强图片的对比度 1 获取图像指针
const uchar* current = Mat对象.ptr<uchar>(row)
获取了 当前图像的 第row行像素的数组 p(row, col) = current[col]
获取了第row行第col列的点 2 像素范围处理 确保值在0到255之间
saturate_cast<uchar>(值)
传入值小于0时候返回0
大于255时候 返回255
在0-255之间 返回正常数 3 定义掩膜
Mat kernel = (Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);
定义了一个3*3大小的掩膜,里面的内容:
[
[ 0,-1, 0 ],
[-1, 5, -1],
[ 0,-1, 0 ]
]
4 掩膜运算
filter2D(src, dst, src.depth(), kernel)
src: 原图像
dst: 输出图像
src.depth() 原图像的深度 32 24 8 等
kernel: 掩膜核
*/ #include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv; int main() {
Mat src, dst;
src = imread("d:/图片/m2.jpg"); // 载入原图像
if (!src.data) { // 如果有读取到
printf("没有找到图片");
return -;
}
// 显示原始图像
namedWindow("输入图片", CV_WINDOW_AUTOSIZE);
imshow("输入图片", src); // 输出图像的初始化 与原图像相同,像素值初始化为0
dst = Mat::zeros(src.size(), src.type()); /*
// 手动实现一个掩膜操作 // 图像的宽度 为 宽度*通道数
int cols = (src.cols) * src.channels(); // 列数 宽度
int rows = src.rows; // 行数 高度
int offsetx = src.channels(); // 通道数 存在列里面 // 掩膜操作没有从0 0 开始是为了把边界让开,掩膜是3*3的, 中间一个是目标位置。
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 - offsetx ; col++) {
// 掩膜运算 并且控制像素值在0到255之间
output[col] = saturate_cast<uchar>( // 控制像素值0到255之间
5 * current[col] - // 当前像素值
(
current[col - offsetx] + // 左边像素值
current[col + offsetx] + // 右边像素值
previous[col]+next[col] // 上合下的像素值
)
);
}
} */
// 计算时间花费
double t = getTickCount(); // 调用掩膜运算
// 初始化一个掩膜
Mat kernel = (Mat_<char>(, ) <<
, -, ,
-, , -,
, -, );
filter2D(src, dst, src.depth(), kernel); // 计算时间花费
double time_cost = (getTickCount() - t) /getTickFrequency();
printf("花费时间:%f", time_cost); namedWindow("掩膜操作", CV_WINDOW_AUTOSIZE);
imshow("掩膜操作", dst); waitKey();
return ;
}
04-02 14:01