- 构造一个目标大小[size_h, size_w]的全0 Mat ResizedImg
- 按照原始图片src长宽比将图片resize到某条边等于目标尺寸,另一条边小于目标尺寸
- 在ResizedImg找到一个Roi区域,大小等于resize后的src,若需要pad宽,则找到roi的宽边起始位置x:
这里假设src中H>W:resize后的src宽为w,则x = (size_w - w) / 2
- 将resize后的src复制到roi中,相当于全0的ResizedImg中有了原图,也就等价于原图左右pad了全0的像素。
void CPreProcess::Resize_with_Pad(Mat srcImg,Mat & ResizedImg,cv::Size size)
//yinyong diaoyong
{
Mat src;
srcImg.copyTo(src);
src.convertTo(src,CV_32FC3);
int H=0,W=0,C=0;
H=src.size().height; //src_image_size
W=src.size().width;
C=src.channels();
int size_w= size.width; // dst_image_size
int size_h= size.height;
assert (size_w==size_h);
// initialization
ResizedImg=cv::Mat::zeros(size,CV_32FC3); // create dst_image and initialization
int h=0,w=0;
if (H>W)
{
float rate=(float)H/W;
h=size_h; //dst_image_size
w=(int)(h/rate); // calculate dst_image_width with src h/w percent before resized
cv::resize(src,src,cv::Size(w,h)); //adjust to h/w percent the same as src_image
Rect rect;
int pad_x=(size_w-w)/2; // w = h/rate = (size_h * W) /H
rect.x=pad_x;
rect.y=0;
rect.width=w;
rect.height=h;
Mat roi=ResizedImg(rect);// select an area of interest in ResizedImg
src.copyTo(roi); // copy src to roi
}
else
{
float rate=(float)H/W;
w=size_w;
h=(int)(w*rate);
cv::resize(src,src,cv::Size(w,h));
Rect rect;
int pad_y=(size_h-h)/2;
rect.x=0;
rect.y=pad_y;
rect.width=w;
rect.height=h;
Mat roi=ResizedImg(rect);
src.copyTo(roi);
}
}
网友评论