C++ opencv实现中心裁剪图片
//你可以使用OpenCV库中的getRectSubPix()函数来实现裁剪图像的功能,它可以以指定的中心点为基准,从图像中提取指定尺寸的子图像。具体的代码如下:
Mat img_src; // 图像原始数据
Mat img_dst; // 目标数据
Point center(width/2, height/2); // 指定的中心点
Size size(60, 60); // 裁剪出的图片大小
getRectSubPix(img_src, size, center, img_dst); // 裁剪出目标图片
方法二:
以裁剪300*300大小为例
void center_resize(cv::Mat &img, cv::Size new_shape)//中心裁剪 new_shape提前定义(300*300)
{
float width = img.cols;
float height = img.rows;
int center_x = round(width / 2);
int center_y = round(height / 2);
int dh = int(round((new_shape.height - height) / 2));
int dw = int(round((new_shape.width - width) / 2));
cv::Scalar color = cv::Scalar(0, 0, 0);//填充色
if (width >= 300 && height >= 300)
{
img = img(cv::Range(center_y - (round(new_shape.height / 2)), center_y + (round(new_shape.height / 2))),
cv::Range(center_x - (round(new_shape.width / 2)), center_x + (round(new_shape.width / 2))));
}
else if (width >= 300)
{
cv::copyMakeBorder(img, img, dh, dh, 0, 0, cv::BORDER_CONSTANT, color);
img = img(cv::Range(0, 300), cv::Range(center_x - (round(new_shape.width / 2)), center_x + (round(new_shape.width / 2))));
}
else if (height >= 300)
{
cv::copyMakeBorder(img, img, 0, 0, dw, dw, cv::BORDER_CONSTANT, color);
img = img(cv::Range(center_y - (round(new_shape.height / 2)), center_y + (round(new_shape.height / 2))), cv::Range(0, 300));
}
else
{
cv::copyMakeBorder(img, img, dh, dh, dw, dw, cv::BORDER_CONSTANT, color);
img = img(cv::Range(0, 300), cv::Range(0, 300));
}
}