ในวิธีก่อนหน้า (วิธี 'at') เราจำเป็นต้องระบุประเภทรูปภาพขณะเข้าถึงค่าพิกเซล มีอีกวิธีหนึ่งที่ง่ายกว่าวิธี 'at' เรียกว่าวิธีการเข้าถึงโดยตรง ในการเข้าถึงค่าพิกเซลโดยใช้วิธีนี้ เราจำเป็นต้องระบุประเภท Mat เช่น Mat
โปรแกรมต่อไปนี้สาธิตวิธีการเปลี่ยนค่าพิกเซลโดยใช้วิธีการเข้าใช้โดยตรงใน OpenCV
ตัวอย่าง
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;//Declaring cv namespace
using namespace std;
void direct_access(Mat_<Vec3b> &image, int n){ //Declaring the 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//
image(j, i) = 0;//setting the pixel values to zero//
}
}
int main() {
Mat_<Vec3b> 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//
direct_access(image, 4000);//calling the direct access function//
imshow("Noisy Image", image);//showing the Noisy image
imshow("Unchanged Image", unchanged_Image);//showing the unchanged image//
waitKey(0);//wait for Keystroke//
return 0;
} ผลลัพธ์
