如何使用 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;
}

输出

更新于: 10-Mar-2021

3K+ 浏览量

职业生涯起航

通过完成课程获得认证

开始
广告
© . All rights reserved.