[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

相关推荐
chen_jared几秒前
opencv和matlab中相机内参标定模型
opencv·matlab·相机内参标定
〝七夜5697 分钟前
Jsp中动态include和静态include的区别
java·开发语言
木土雨成小小测试员9 分钟前
Python测试开发之跨域请求
开发语言·python
努力进修13 分钟前
【JavaEE初阶】告别小白!Java IO 流读写 + 文件操作实战
java·开发语言·java-ee
沐知全栈开发13 分钟前
Vue3 Ajax(Axios)详解
开发语言
dllmayday13 分钟前
QWidget上叠加半透明QML组件显示方案
开发语言·qt5
羑悻的小杀马特13 分钟前
C++多线程同步工具箱:call_once精准触发、lock_guard/unique_lock智能管理,打造无死锁程序!
c++·多线程·死锁·lock_guard·unique_lock·call_once
电子_咸鱼13 分钟前
【QT——信号和槽(1)】
linux·c语言·开发语言·数据库·c++·git·qt
deephub19 分钟前
PyCausalSim:基于模拟的因果发现的Python框架
开发语言·python·机器学习·因果发现
weixin_3077791319 分钟前
Jenkins Declarative Pipeline:现代CI/CD的声明式实践指南
开发语言·ci/cd·自动化·jenkins·etl