發現Mat類中的at方法對於獲取圖像矩陣某點的RGB值或者改變某點的值很方便,對於單通道的圖像,則可以使用:
<span style="font-size:18px;">image.at<uchar>(i, j)</span>
<span style="font-size:18px;">image.at<Vec3b>(i, j)[0] image.at<Vec3b>(i, j)[1] image.at<Vec3b>(i, j)[2]</span>
<span style="font-size:18px;">#include<opencv2\opencv.hpp> using namespace cv; using namespace std; void salt_noise(Mat image, int time) { for (int k = 0; k < time; k++)//time is the number of the noise you add { int i = rand() % image.rows; int j = rand() % image.cols; if (image.channels() == 1)//single channel { image.at<uchar>(i, j) = rand() % 255; } else if (image.channels() == 3)//RGB channel { image.at<Vec3b>(i, j)[0] = rand() % 255; image.at<Vec3b>(i, j)[1] = rand() % 255; image.at<Vec3b>(i, j)[2] = rand() % 255; } } } int main(void) { Mat image = imread("..\\lena.bmp", 0); if (image.empty()) { cout << "load image error" << endl; return -1; } salt_noise(image, 3000); namedWindow("image", 1); imshow("image", image); waitKey(); return 0; }</span>
不過貌似用at取值或改變值來做比較耗時,當然我們還可以使用Mat的模板子類Mat_<T>,,對於單通道的具體使用:
<span style="font-size:18px;">Mat_<uchar> img = image; img(i, j) = rand() % 255;</span>對於RGB通道的使用:
<span style="font-size:18px;">Mat_<Vec3b> img = image; img(i, j)[0] = rand() % 255; img(i, j)[1] = rand() % 255; mg(i, j)[2] = rand() % 255;</span>
還可以用指針的方法遍歷每一像素:(耗時較小)
<span style="font-size:18px;">void colorReduce(Mat image, int div = 64) { int nrow = image.rows; int ncol = image.cols*image.channels(); for (int i = 0; i < nrow; i++) { uchar* data = image.ptr<uchar>(i);//get the address of row i; for (int j = 0; j < ncol; j++) { data[i] = (data[i] / div)*div ; } } }</span>
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。