如何在OpenCV中使用指针方法减少颜色?


在图像处理中,我们对图像进行计算。更具体地说,我们对像素进行计算,因此像素数量越多,计算时间就越长。为了减少计算时间,我们需要高效地扫描图像。我们将学习如何使用指针实现高效的图像扫描循环。

在这里,我们将看到一个颜色减少策略的像素扫描过程示例。彩色图像(如RGB图像)由3个通道组成。这些通道中的每一个都具有相同数量的像素,但具有相应的值。每个值都是一个8位无符号字符值。

因此,可能的颜色总数为256 x 256 x 256 = 16,777,216。我们可以将每个像素的值除以大小相等的立方体来减少这个巨大的可能颜色数。如果我们使用8 x 8 x 8的立方体进行划分,则可能的颜色数变为32 x 32 x 32 = 32,768。

当颜色数量减少时,系统速度就会加快。为了执行此减少操作,我们需要扫描每个像素,这是一个耗时的任务。这就是为什么我们需要一种高效的图像扫描方法。

以下程序演示了如何在OpenCV中使用指针方法减少颜色。

示例

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;//Declaring cv namespace
using namespace std;//Declaring std namespace
void reducing_Color(Mat &image, int div=64){ //Declaring the function//
   int   total_rows = image.rows;//getting the number of lines//
   int total_columns = image.cols * image.channels();//getting the number of columns per line//
   for (int j = 0; j < total_rows; j++){ //initiating a for loop for rows
      uchar* data = image.ptr<uchar>(j);
      for (int i = 0; i < total_columns; i++){ //initiating a for loop for columns//
         data[i] = data[i] / div * div + div / 2;//processing the pixels//
      }
   }  
}
int main() {
   Mat image;//taking an image matrix//
   image = imread("grapes.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;
}

输出

更新于:2021年3月10日

408 次查看

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.