[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

相关推荐
Dream it possible!8 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
星释8 小时前
Rust 练习册 22:映射函数与泛型的威力
开发语言·rust·机器人
云泽8088 小时前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list
xlq223228 小时前
15.list(上)
数据结构·c++·list
云帆小二8 小时前
从开发语言出发如何选择学习考试系统
开发语言·学习
光泽雨9 小时前
python学习基础
开发语言·数据库·python
Elias不吃糖9 小时前
总结我的小项目里现在用到的Redis
c++·redis·学习
AA陈超9 小时前
使用UnrealEngine引擎,实现鼠标点击移动
c++·笔记·学习·ue5·虚幻引擎
百***06019 小时前
python爬虫——爬取全年天气数据并做可视化分析
开发语言·爬虫·python
jghhh0110 小时前
基于幅度的和差测角程序
开发语言·matlab