文章目录
- 掩膜操作提高图像的对比度
- 获取图像像素制作
- 图像掩膜算子
- 防止像素溢出算子
- 全部代码
掩膜操作提高图像的对比度
红色是中心像素,从上到下,从左到右对每个像素做同样的处理操作,得到最终结果就是对比度提高之后的输出图像Mat对象
注:相当于用一个刷子把图像的每隔几点的颜色增强(理解就行),以下为代码表达
int cols = (src.cols-1) * src.channels();//src.cols 为图像的列int offsetx = 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]));}}
获取图像像素制作
- CV_Assert(myImage.depth() == CV_8U); (OpenCV 中的 CV_Assert 函数来执行一个断言,用于确保 myImage 的深度是 CV_8U。在这种情况下,它检查 myImage 是否是一个8位无符号整数类型的图像。如果条件不满足,程序将会终止并输出错误信息。这可以帮助程序员在开发过程中及早捕获到一些潜在的问题。)
- Mat.ptr(int i=0) 获取像素矩阵的指针,索引i表示第几行,从0开始计行数。
- 获得当前行指针const uchar* current= myImage.ptr(row );
- 获取当前像素点P(row, col)的像素值 p(row, col) =current[col]
图像掩膜算子
filter2D 掩码算子
filter2D(InputArray src,OutputArray dst,int ddepth,InputArray kernel,…)
src为输入图像。
dst为目标图像,其尺寸和通道与输入图像一致。
ddepth期望的目标图像类型,即位图深度。其中输出图像的位图深度应该大于或者等于输入图像的位图深度。值为-1时表示与原图(即src)的位图深度一样。
定义掩膜(例如定义一个3.2部分中所示的掩膜):Mat Kernel=(Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0)
防止像素溢出算子
saturate_cast()
在图像处理方面,无论是加是减,乘除,都会超出一个像素灰度值的范围(0~255),saturate_cast函数的作用即是:当运算完之后,结果为负,则转为0,结果超出255,则为255。
全部代码
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{Mat src = imread("test.jpg");//读取图片if (src.empty()){cout << "could not load src...";return -1;}namedWindow("test");//设置窗口名称imshow("test", src);/*int cols = (src.cols-1) * src.channels();int offsetx = 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]));}}*/Mat dst;double t = getTickCount();Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);filter2D(src, dst, src.depth(), kernel);double timeconsume = (getTickCount() - t) / getTickFrequency();printf("tim consume %.2f\n", timeconsume);namedWindow("contrast image demo");imshow("contrast image demo", dst);waitKey(0);return 0;
}