圖像處理(二)
矩陣的掩膜操作
- 獲取圖像像素指針
- 掩膜操作
獲取圖像像素指針
CV_Assert(myImage.depth() == CV_8U);
Mat.ptr(int i=0) 獲取像素矩陣的指針,索引i表示第幾行,從0開始計行數。
獲得當前行指針const uchar* current= myImage.ptr(row );
獲取當前像素點P(row, col)的像素值 p(row, col) =current[col]
注意:這裏的row和col是像素點的行和列,在MAT類中定義的
像素範圍處理saturate_cast
saturate_cast(-100),返回 0。
saturate_cast(288),返回255
saturate_cast(100),返回100
這個函數的功能是確保RGB值得範圍在0~255之間
保證能夠正常輸出
什麼是掩膜操作呢?
掩膜操作實現圖像對比度調整-紅色是中心像素,從上到下,從左到右對每個像素做同樣的處理操作,得到最終結果就是對比度提高之後的輸出圖像Mat對象,通俗來說就是提高照片的對比度
注:每一個像素點的對比度提高都是通過相鄰的四個像素點來進行矩陣計算的
掩膜矩陣計算代碼
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]));
}
}
以上代碼瞭解一下即可,一般可以使用filter2D函數計算
函數調用filter2D功能
定義掩膜:Mat kernel = (Mat_(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D( src, dst, src.depth(), kernel );其中src與dst是Mat類型變量、src.depth表示位圖深度,有32、24、8等。
具體代碼實現
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("D:/vcprojects/images/test.png");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src);
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;
}