OpenCV - 小技巧

1、  图像的遍历

OpenCV图像遍历最高效的方法是指针遍历方法。因为图像在OpenCV里的存储机制问题,行与行之间可能有空白单元(一般是补够4的倍数或8的倍数,有些地方也称作“位对齐”)。这些空白单元对图像来说是没有意思的,只是为了在某些架构上能够更有效率,比如intel MMX可以更有效的处理那种个数是4或8倍数的行。Mat提供了一个检测图像是否连续的函数isContinuous()。当图像连通时,我们就可以把图像完全展开,看成是一行。因此最高效的遍历方法如下:

void imageCopy(const Mat& image,Mat& outImage) {   
	int nr=image.rows;    
	int nc=image.cols;    
	outImage.create(image.size(),image.type());    
	if(image.isContinuous()&&outImage.isContinuous()) {
		nr=1;
		nc=nc*image.rows*image.channels();
	} 

	for(int i=0;i<nr;i++) 	{     
		const uchar* inData=image.ptr<uchar>(i);       
		uchar* outData=outImage.ptr<uchar>(i);      
		for(int j=0;j<nc;j++) {
			*outData++=*inData++;
		}
	}
}

	// create the accumulation histograms, img is a binary image, t is 水平或垂直
	Mat CalcHistogram(Mat img, int t) {
		int sz = (t) ? img.rows : img.cols;
		Mat mhist = Mat::zeros(1, sz, CV_32F);
		for(int j = 0; j < sz; j++){
			Mat data = (t) ? img.row(j) : img.col(j);
			// 统计这一行或一列中,非零元素的个数,并保存到mhist中
			mhist.at<float>(j) = countNonZero(data);
		}

		double min, max;
		// Normalize histogram
		minMaxLoc(mhist, &min, &max);
		if (max > 0){
			// 用mhist直方图中的最大值,归一化直方图
			mhist.convertTo(mhist, -1, 1.0f/max, 0);
		}

		return mhist;
	}
	//! 获得字符的特征图
	Mat features(Mat in, int sizeData) {
		//Histogram features
		Mat vhist = ProjectedHistogram(in, VERTICAL);
		Mat hhist = ProjectedHistogram(in, HORIZONTAL);

		//Low data feature
		Mat lowData;
		resize(in, lowData, Size(sizeData, sizeData));
		//Last 10 is the number of moments components
		int numCols = vhist.cols + hhist.cols + lowData.cols * lowData.cols;
		Mat out = Mat::zeros(1, numCols, CV_32F);
		//Asign values to feature, ANN的样本特征为水平、垂直直方图和低分辨率图像所组成的矢量
		int j = 0;
		for(int i = 0; i < vhist.cols; i++){
			out.at<float>(j) = vhist.at<float>(i);
			j++;
		}

		for(int i = 0; i < hhist.cols; i++){
			out.at<float>(j) = hhist.at<float>(i);
			j++;
		}

		for(int x=0; x<lowData.cols; x++){
			for(int y=0; y<lowData.rows; y++){
				out.at<float>(j)=(float)lowData.at<unsigned char>(x,y);
				j++;
			}
		}

		return out;
	}



 

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值