opencv函数之saturate_cast(防止溢出)

首先举个例子:

uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
在图像处理方面,无论是加是减,乘除,都会超出一个像素灰度值的范围(0~255),saturate_cast函数的作用即是:当运算完之后,结果为负,则转为0,结果超出255,则为255。

举一个拉普拉斯锐化的例子:对于求一个锐化后的像素点(sharpened_pixel),这个基于拉普拉斯算子的简单算法主要是遍历图像中的像素点,根据领域像素确定其锐化后的值,计算公式:sharpened_pixel = 5 * current – left – right – up – down ; 

#include <iostream>    
#include<core/core.hpp>    
#include<highgui/highgui.hpp>    
using namespace cv;

void sharpen(const Mat& img, Mat& result)
{
	result.create(img.size(), img.type());
	//处理边界内部的像素点, 图像最外围的像素点暂不处理
	for (int row = 1; row < img.rows - 1; row++)
	{
		//前一行像素点
		const uchar* previous = img.ptr<const uchar>(row - 1);
		//待处理的当前行
		const uchar* current = img.ptr<const uchar>(row);
		//下一行
		const uchar* next = img.ptr<const uchar>(row + 1);
		uchar *output = result.ptr<uchar>(row);
		int ch = img.channels();
		int starts = ch;
		int ends = (img.cols - 1) * ch;
		for (int col = starts; col < ends; col++)
		{
			//输出图像的遍历指针与当前行的指针同步递增, 以每行的每一个像素点的每一个通道值为一个递增量, 因为要考虑到图像的通道数
			*output++ = saturate_cast<uchar>(5 * current[col] - current[col - ch] - current[col + ch] - previous[col] - next[col]);
		}
	} 
	//外围像素点设为 0
	result.row(0).setTo(Scalar::all(0));
	result.row(result.rows - 1).setTo(Scalar::all(0));
	result.col(0).setTo(Scalar::all(0));
	result.col(result.cols - 1).setTo(Scalar::all(0));
}

int main()
{
	Mat kobe = imread("F://IM_VIDEO//kobe.jpg");
	Mat sharpenedKobe;
	sharpen(kobe, sharpenedKobe);

	imshow("kobe", kobe);
	imshow("sharpened kobe", sharpenedKobe);
	cvWaitKey();
	return 0;
}

其中,关于像素操作部分可以参见:http://blog.csdn.net/piaoxuezhong/article/details/54236227

参考:

http://blog.csdn.net/mjlsuccess/article/details/12401839

http://blog.csdn.net/poem_qianmo/article/details/20537737

http://blog.csdn.net/mvtechnology/article/details/8139272

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值