ในภาพระดับสีเทา ค่าพิกเซลเป็นค่าตัวเลขเดียว แต่ในภาพสี เช่น ภาพ RGB พิกเซลเป็นเวกเตอร์ที่มีสามค่า ค่าทั้งสามนี้แสดงถึงสามช่อง
ที่นี่เราจะสร้างฟังก์ชันที่เข้าถึงทั้งภาพระดับสีเทาและค่าพิกเซลภาพ RGB และสุ่มเพิ่มจุดรบกวนให้กับพิกเซลของภาพ จากนั้นเราเรียกใช้ฟังก์ชันภายในฟังก์ชัน main() เพื่อสังเกตผลลัพธ์
โปรแกรมต่อไปนี้สาธิตวิธีการเปลี่ยนค่าพิกเซลโดยใช้วิธี 'at' ใน OpenCV
ตัวอย่าง
#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;
} ผลลัพธ์
