[C++][opencv]基于opencv实现photoshop算法图像剪切

【测试环境】

vs2019

opencv==4.8.0

【效果演示】

【核心实现代码】

复制代码
//图像剪切
//参数:src为源图像, dst为结果图像, rect为剪切区域
//返回值:返回0表示成功,否则返回错误代码
int imageCrop(InputArray src, OutputArray dst, Rect rect)
{
	Mat input = src.getMat();
	if (input.empty()) {
		return -1;
	}

	//计算剪切区域:  剪切Rect与源图像所在Rect的交集
	Rect srcRect(0, 0, input.cols, input.rows);
	rect = rect & srcRect;
	if (rect.width <= 0 || rect.height <= 0) return -2;

	//创建结果图像
	dst.create(Size(rect.width, rect.height), src.type());
	Mat output = dst.getMat();
	if (output.empty()) return -1;

	try {
		//复制源图像的剪切区域 到结果图像
		input(rect).copyTo(output);
		return 0;
	}
	catch (...) {
		return -3;
	}
}

//========================  主程序开始 ==========================

static string window_name = "Draw a Rect to crop";
static Mat src;  //源图片
bool  isDrag = false;
Point point1; //矩形的第一个点
Point point2; //矩形的第二个点

static void callbackMouseEvent(int mouseEvent, int x, int y, int flags, void* param)
{
	switch (mouseEvent) {

	case EVENT_LBUTTONDOWN:
		point1 = Point(x, y);
		point2 = Point(x, y);
		isDrag = true;
		break;

	case EVENT_MOUSEMOVE:
		if (isDrag) {
			point2 = Point(x, y);
			Mat dst = src.clone();
			Rect rect(point1, point2); //得到矩形
			rectangle(dst, rect, Scalar(0, 0, 255));//画矩形
			imshow(window_name, dst); //显示图像
		}
		break;

	case EVENT_LBUTTONUP:
		if (isDrag) {
			isDrag = false;
			Rect rect(point1, point2); //得到矩形
			imageCrop(src, src, rect); //图像剪切
			imshow(window_name, src); //显示图像
		}
		break;

	}

	return;
}

【完整演示代码下载】

https://download.csdn.net/download/FL1623863129/89633023

相关推荐
CodeCraft Studio1 天前
国产化Excel开发组件Spire.XLS教程:Python将列表导出为CSV文件(含一维/二维/字典列表)
开发语言·python·excel·csv·spire.xls·列表导出为csv
guygg881 天前
Alpha稳定分布概率密度函数的MATLAB实现
开发语言·matlab
草莓熊Lotso1 天前
C++ 二叉搜索树(BST)完全指南:从概念原理、核心操作到底层实现
java·运维·开发语言·c++·人工智能·经验分享·c++进阶
oliveira-time1 天前
单例模式中的饿汉式
java·开发语言
Go away, devil1 天前
Java-----集合
java·开发语言
VBA63371 天前
VBA即用型代码手册:利用函数保存为PDF文件UseFunctionSaveAsPDF
开发语言
say_fall1 天前
C语言编程实战:每日刷题 - day2
c语言·开发语言·学习
上去我就QWER1 天前
Qt快捷键“魔法师”:QKeySequence
开发语言·c++·qt
Pluto_CSND1 天前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
将编程培养成爱好1 天前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式