下面的代码实现图像对比度的调整。效果见后面的图片。
其实勇哥认为这个实现的是图片锐化效果,如果用photoshop来做对比,实现的就是锐化滤镜的效果。
而photoshop的对比度效果与这个是是不同的。
代码说明:
(1)注释的代码用来操作图片中的像素。这也是数据类型Mat的一个功能。
CV_Assert(myImage.depth() == CV_8U); 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>用来把数据限制在0-255范围内,这个范围刚好是RGB一个通道的取值范围。
saturate_cast<uchar>(-100),返回 0。 saturate_cast<uchar>(288),返回255 saturate_cast<uchar>(100),返回100 这个函数的功能是确保RGB值得范围在0~255之间
(3)filter2D函数实现的就是注释代码中的功能。
1.定义掩膜:Mat kernel = (Mat_<char>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); 2.filter2D( src, dst, src.depth(), kernel ); 其中src与dst是Mat类型变量、src.depth表示位图深度,有32、24、8等。
(4)掩码操作的说明
掩膜操作实现了图像对比度调整,过程是这样的:
如下图所示,红色是中心像素,从上到下,从左到右对每个像素做同样的处理操作,得到最终结果就是对比度提高之后的输出图像Mat对象。

数学算法说明如下:

代码:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("e:/5.png");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", 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]));
}
}
*/
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", CV_WINDOW_AUTOSIZE);
imshow("contrast image demo", dst);
waitKey(0);
return 0;
}
图片像素级的操作,对于勇哥的专业来讲是没啥子意义的,因为工业视觉方面应该没有这方面的应用。
但是这部分内容是opencv的基础,其它部分是基立在这些基础之上的,因此还是有必要花些时间来研究的。
---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文章代码及资料部分或全部来自贾志刚老师的视频,勇哥只是在个人理解的基础上做学习笔记,转载请附上博文链接!


少有人走的路



















