OpenCV学习二:指针操作、saturate_cast

本文介绍了一种使用OpenCV库进行图像边缘检测的方法。通过应用特定的数学运算符来增强图像边界,该程序实现了对输入图像的有效处理并生成了两个不同的输出图像。文章还讨论了如何避免在计算过程中可能出现的整数溢出问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <opencv2/opencv.hpp>
#include  <stdio.h>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
	Mat img = imread("123.jpg",-1);
	int cols = (img.cols - 1)*img.channels();
	//列,乘以 img.channels() 是因为有RGB三个通道,减一是因为mask 矩阵为3*3 上下左右各有一列(行)触及不到。
	int rows = img.rows;//行。
	int offset = img.channels();//RGB img.channels() = 3;
 	Mat out1,out2;
 	out1 = Mat::zeros(img.size(),img.type());
	out2 = Mat::zeros(img.size(),img.type());

	for (int row = 1;row<(rows - 1);row++)
	{
		const uchar* previous = img.ptr<uchar>(row-1);
		const uchar* current = img.ptr<uchar>(row);
		const uchar* next = img.ptr<uchar>(row+1);
		uchar* output1 = out1.ptr<uchar>(row);
		uchar* output2 = out2.ptr<uchar>(row);

		for (int col = offset; col<cols;col++)
		{
			output1[col] = 5*current[col] - current[col-offset] - current[col+offset] - previous[col] - next[col];
			output2[col] = saturate_cast<uchar>(5*current[col] - current[col-offset] - current[col+offset] - previous[col] - next[col]) ;
			//output2[col] = saturate_cast<uchar>(output1[col]) ;  //这么写哪里有问题?
		}
	}



	imshow("1",out1);
	imshow("2",out2);

	imwrite("t1.jpg",out1);
	imwrite("t2.jpg",out2);
	waitKey();
	return 1;
}
之前的

增加防止溢出saturate_cast


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值