OpenCV.2.Computer.Vision.Application.Programming.Cookbook--Scanning an image with pointers

來源:互聯網
上載者:User

標籤:

#include<opencv2\opencv.hpp>void colorReduce(cv::Mat &image, int div=64) {  int nr= image.rows; // number of rows  int nc= image.cols * image.channels(); // total number of elements per line  for (int j=0; j<nr; j++){  // get the address of row j//ptr:It is a template method that returns the address of row number j:uchar* data= image.ptr<uchar>(j);  for (int i=0; i<nc; i++) {  //we could have equivalently used pointer arithmetic to move from column to column// process each pixel ---------------------//data[i]= data[i]/div*div + div/2;  //data[i]= data[i]-data[i]%div + div/2;// mask used to round the pixel valueint n=6;uchar mask= 0xFF<<n;data[i]=(data[i]&mask) + div/2;// e.g. for div=16, mask= 0xF0// end of pixel processing ----------------}                    }  }  int main(int argc,char* argv[]){cv::Mat pImg;pImg=cv::imread("lena.jpg");cv::namedWindow("Image");cv::imshow("Image",pImg);colorReduce(pImg);cv::namedWindow("pImg");cv::imshow("pImg",pImg);cv::waitKey(0);cv::destroyWindow("Image");return 0;}



color reduction is achieved by taking advantage of an integer division that floors the division result to the nearest lower integer:       

data[i]= data[i]/div*div + div/2;


The reduced color could have also been computed using the modulo operator which brings us to the nearest multiple of div (the 1D reduction factor):    

data[i]= data[i] – data[i]%div + div/2;
But this computation is a bit slower because it requires reading each pixel value twice.


Another option would be to use bitwise operators. Indeed, if we restrict the reduction factor to a power of 2, that is, div=pow(2,n), then masking the first n bits of the pixel value would give us the nearest lower multiple of div. This mask would be computed by a simple bit shift:
// mask used to round the pixel value
uchar mask= 0xFF<<n;

 // e.g. for div=16, mask= 0xF0

The color reduction would be given by:    

data[i]= (data[i]&mask) + div/2;
In general, bitwise operations lead to very efficient code, so they could constitute a powerful alternative when efficiency is a requirement.



OpenCV.2.Computer.Vision.Application.Programming.Cookbook--Scanning an image with pointers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.