如何使用 OpenCV 中的“at”方法更改畫素值?
在灰度影像中,畫素值是一個數字值。但在彩色影像(如 RGB 影像)中,畫素是一個包含三個值的向量。這三個值代表三個通道。
此處我們將建立一個函式,該函式訪問灰度影像和 RGB 影像畫素值,並隨機向影像畫素新增噪聲。然後我們在 main() 函式中呼叫該函式,觀察結果。
以下程式演示瞭如何使用 OpenCV 中的“at”方法更改畫素值。
示例
#include<iostream> #include<opencv2/highgui/highgui.hpp> using namespace cv;//Declaring cv namespace using namespace std; void adding_Noise(Mat& image, int n){ //'adding_Noise' function// for (int x = 0; x < n; x++){ //initiating a for loop// int i = rand() % image.cols;//accessing random column// int j = rand() % image.rows;//accessing random rows// if (image.channels() == 1){ //apply noise to grayscale image// image.at<uchar>(j, i) = 0;//Changing the value of pixel// } if (image.channels() == 3){ //apply noise to RGB image// image.at<Vec3b>(j, i)[0] = 0;//Changing the value of first channel// image.at<Vec3b>(j, i)[1] = 0;//Changing the value of first channel// image.at<Vec3b>(j, i)[2] = 0;//Changing the value of first channel// } } } int main() { Mat image;//taking an image matrix// Mat unchanged_Image;//taking another image matrix// image = imread("sky.jpg");//loading an image// unchanged_Image = imread("sky.jpg");//loading the same image// namedWindow("Noisy Image");//Declaring an window// namedWindow("Unchanged Image");//Declaring another window// adding_Noise(image, 4000);//calling the 'adding_Noise' function// imshow("Noisy Image", image);//showing the Noisy image imshow("Unchanged Image",unchanged_Image);//showing the unchanged image// waitKey(0);//wait for Keystroke// destroyAllWindows();//return all allocated memory return 0; }
輸出
廣告