Computer >> Máy Tính >  >> Lập trình >> C ++

Làm cách nào để giảm màu bằng phương pháp Iterator trong OpenCV?

OpenCV có lớp 'Mat iterator' tương thích với C ++ STL. Sử dụng lớp 'Mat iterator' này, chúng ta có thể truy cập các pixel rất dễ dàng. Chúng ta phải tạo một đối tượng của lớp 'Mat iterator'. Chúng ta có thể làm điều đó như 'Mat_ ::ví dụ về trình lặp'. Chúng ta phải sử dụng dấu gạch dưới sau 'Mat' như 'Mat_' vì nó là một phương thức khuôn mẫu. Trong phương thức này, kiểu trả về phải được chỉ định trong khi tạo một đối tượng của lớp 'iterator'. Đó là lý do tại sao chúng tôi đã khai báo kiểu dữ liệu .

Chương trình sau đây trình bày cách giảm màu bằng phương pháp Iterator trong OpenCV.

Ví dụ

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace std;//Declaring std namespace
using namespace cv;//Declaring cv namespace
void reducing_Color(Mat& image, int div = 64){ //Declaring the function//
   Mat_<Vec3b>::iterator iterator_start;//Declaring starting iterator//
   iterator_start = image.begin<Vec3b>();//Obtain iterator at initial position//
   Mat_<Vec3b>::iterator iterator_end;//Declaring ending iterator//
   iterator_end = image.end<Vec3b>();//Obtain iterator an end position//
   for (; iterator_start != iterator_end; iterator_start++){ //Loop for all pixels//
      (*iterator_start)[0] = (*iterator_start)[0] / div * div + div / 2;//Process pixels of first channel//
      (*iterator_start)[1] = (*iterator_start)[1] / div * div + div / 2;//Process pixels of second channel//
      (*iterator_start)[2] = (*iterator_start)[2] / div * div + div / 2;//Process pixels of third channel//
   }
}
int main() {
   Mat image;//taking an image matrix//
   image = imread("mango.jpg");//loading an image//
   namedWindow("Image Window");//Declaring another window//
   reducing_Color(image);//calling the function//
   imshow("Image Window", image);//showing the image with reduced color//
   waitKey(0);
   return 0;
}

Đầu ra

Làm cách nào để giảm màu bằng phương pháp Iterator trong OpenCV?