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));
    }
     
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值