Opencv之像素值的获取
灰度图像${\rm{M}} \times {\rm{N}}$的像素矩阵值为0~255,像素值越大越亮。${{\rm{I}}_{{\rm{i}}{\rm{j}}}}$,i表示行的位置,j 表示列的位置即i行j列。RGB图像在Opencv中内存顺序为:BGR三个通道。
获取像素的方式有三种:代码如下
1 #include<opencv2/opencv.hpp> 2 #include<iostream> 3 4 using namespace std; 5 using namespace cv; 6 void point(Mat& inputImage, Mat& result, int div);//指针方式 7 void iteraton_operate(Mat& inputImage, Mat& result, int div);//迭代器方式 8 void dynamic_address(Mat& inputImage, Mat& result, int div);//动态地址方式 9 Mat src, gray, dst; 10 int main(int argc, char** argv) 11 { 12 13 src = imread("H:/cv_code/image/home.jpg"); 14 if (src.empty()) 15 { 16 printf("could not find image"); 17 return -1; 18 } 19 namedWindow("input"); 20 imshow("input",src); 21 cvtColor(src,gray,COLOR_BGR2GRAY); 22 namedWindow("result"); 23 point(src, dst, 32); 24 iteraton_operate(src, dst, 32); 25 dynamic_address(src, dst, 32); 26 waitKey(0); 27 return 0; 28 } 29 void point(Mat& inputImage, Mat& result, int div) 30 { 31 result = inputImage.clone(); 32 int channels = result.channels(); 33 int rows = result.rows; 34 int cols = result.cols * channels; 35 for (int i = 0; i < rows; i++) 36 { 37 uchar* value = result.ptr<uchar>(i); 38 for (int j = 0; j < cols; j++) 39 { 40 value[j] = value[j] / div * div + div / 2; 41 } 42 } 43 } 44 void iteraton_operate(Mat& inputImage, Mat& result, int div) 45 { 46 result = inputImage.clone(); 47 Mat_<Vec3b>::iterator itbegin = result.begin<Vec3b>(); 48 Mat_<Vec3b>::iterator itend = result.end<Vec3b>(); 49 for (;itbegin !=itend;++itbegin) 50 { 51 (*itbegin)[0] = (*itbegin)[0] / div * div + div / 2; 52 (*itbegin)[1] = (*itbegin)[1] / div * div + div / 2; 53 (*itbegin)[2] = (*itbegin)[2] / div * div + div / 2; 54 55 } 56 57 } 58 void dynamic_address(Mat& inputImage, Mat& result, int div) 59 { 60 result = inputImage.clone(); 61 int rows = result.rows; 62 int cols = result.cols; 63 for (int i = 0; i < rows; i++) 64 { 65 66 for (int j = 0; j < cols; j++) 67 { 68 result.at<Vec3b>(i, j)[0] = result.at<Vec3b>(i, j)[0] / div * div + div / 2; 69 result.at<Vec3b>(i, j)[1] = result.at<Vec3b>(i, j)[1] / div * div + div / 2; 70 result.at<Vec3b>(i, j)[2] = result.at<Vec3b>(i, j)[2] / div * div + div / 2; 71 } 72 } 73 }