OpenCV.2.Computer.Vision.Application.Programming.Cookbook--Efficient scanning of continuous images

#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  
	if (image.isContinuous())  
	{  
		// then no padded pixels  
		nc= nc*nr;   
		nr= 1;  // it is now a 1D array  
	}  
	int n= static_cast<int>(log(static_cast<double>(div))/log(2.0));  
	// mask used to round the pixel value  
	uchar mask= 0xFF<<n; // e.g. for div=16, mask= 0xF0  
	for (int j=0; j<nr; j++) 
	{  
		uchar* data= image.ptr<uchar>(j);  
		for (int i=0; i<nc; i++) 
		{  
			*data++= *data&mask + div/2;  
		} // end of row                   
	}  
}  

int main(int argc,char* argv[])
{
	cv::Mat pImg;

	pImg=cv::imread("lena.jpg");
	cv::imshow("Image",pImg);

	colorReduce(pImg);

	cv::imshow("pImg",pImg);
	cv::waitKey(0);
	return 0;
}



Mat::reshape
在无需复制数据的前提下改变2D矩阵的形状和通道数或其中之一。
C++: Mat Mat::reshape(int cn, int rows=0) const
参数:
cn – 新的通道数。若cn=0,那么通道数就保持不变。
rows –新的行数。 若rows = 0, 那么行数保持不变。

if (image.isContinuous())
	{
		image.reshape(1,image.cols*image.rows);
	}
	int nr= image.rows; // number of rows  
	int nc= image.cols * image.channels(); // total number of elements per line  
和上面一样效果!

你可能感兴趣的:(OpenCV.2.Computer.Vision.Application.Programming.Cookbook--Efficient scanning of continuous images)