[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

相关推荐
xlp666hub16 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网17 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub19 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星20 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus5 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
IVEN_6 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
blasit7 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip