[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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FL1623863129

你的打赏是我写文章最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值