OpenCV4.0学习笔记(2)腌膜处理
腌膜理解
在最近学习了opencv图像的腌膜处理方法。
在我在学习的过程对于图像腌膜处理的理解即是:
腌膜其实相当于一个滤波,对图片进行处理
类似在修图软件中的将图片锐化,调高对比度,使得图像更加的清晰。
因为图像是由一个个的像素点组成的,腌膜在图片中提取出一块3*3的小矩阵,将小矩阵中的像素值按比例重新计算,使得对比度更高。
原理:
腌膜在opencv中的使用
在opencv4.0中使用方法和旧版本的使用方法一致.
但是同样的不需要额外使用namedWindow函数重新打开窗口,可以直接使用imshow函数显示函数
在原理上掩膜是使用指针提取出图像的像素点,通过对rows和colum根据掩膜的数学公式对3*3的像素矩阵进行处理;
int cols = (img.cols - 1) * img.channels();
int offsetx = img.channels();
int rows = img.rows;
dst = Mat::zeros(img.size(), img.type());
for (int row = 1 ; row < (rows - 1); row++)
{
const uchar*previous = img.ptr<uchar>(row - 1);
const uchar*current = img.ptr<uchar>(row);
const uchar*next = img.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]));
}
}
filter2D函数
但是在实际操作中有更加简单的操作方式,通过调用函数filter2D直接调用刚才定义的掩膜对图像进行处理。
即:
第一步:定义要使用的腌膜
第二步:调用filter2D函数用已经定义好的好、腌膜对图像进行处理
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D(img, dst, img.depth(), kernel);
saturate_cast< uchar >()函数
对于图像的处理过程中经常出现图像中的某些点的像素值超出或者跌出0-255之间,导致图片部分区域变成沙粒状。
而saturate_cast_< char >函数则可以保证图像RGB的值位于0-255之间。
如
saturate_cast<uchar>(-100); //该点的像素值会返回0
saturate_cast<ucahr>(288); //该点的像素值会返回255
saturate_casr<uchar>(100); //改点的像素值会返回100
本次学习所练习的代码为:
#include<opencv2\opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
int main(int arge, char** argv)
{
Mat img, dst;
img = imread("E:\\VOC2007\\JPEGImages\\0001.jpg", 1);
if (img.empty())
{
printf("could not show the image...");
return -1;
}
imshow("opencv setup done", img);
/*
int cols = (img.cols - 1) * img.channels();
int offsetx = img.channels();
int rows = img.rows;
dst = Mat::zeros(img.size(), img.type());
for (int row = 1 ; row < (rows - 1); row++)
{
const uchar*previous = img.ptr<uchar>(row - 1);
const uchar*current = img.ptr<uchar>(row);
const uchar*next = img.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 kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D(img, dst, img.depth(), kernel);
imshow("the changed image", dst);
waitKey(0);
return 0;
}