效果圖如下:
變換前:
變換後:
代碼如下:
struct object_rect {
int x;
int y;
int width;
int height;
};
int resize_uniform(Mat &src, Mat &dst, Size dst_size, object_rect &effect_area)
{
int w = src.cols;
int h = src.rows;
int dst_w = dst_size.width;
int dst_h = dst_size.height;
std::cout << "src: (" << h << ", " << w << ")" << std::endl;
dst = Mat(Size(dst_w, dst_h), CV_8UC1, Scalar(1));
float ratio_src = w*1.0 / h;
float ratio_dst = dst_w*1.0 / dst_h;
int tmp_w = 0;
int tmp_h = 0;
if (ratio_src > ratio_dst) {
tmp_w = dst_w;
tmp_h = floor((dst_w*1.0 / w) * h);
}
else if (ratio_src < ratio_dst) {
tmp_h = dst_h;
tmp_w = floor((dst_h*1.0 / h) * w);
}
else {
resize(src, dst, dst_size);
effect_area.x = 0;
effect_area.y = 0;
effect_area.width = dst_w;
effect_area.height = dst_h;
return 0;
}
std::cout << "tmp: (" << tmp_h << ", " << tmp_w << ")" << std::endl;
Mat tmp;
resize(src, tmp, Size(tmp_w, tmp_h));
tmp.convertTo(tmp,CV_8UC1);
if (tmp_w != dst_w) { //高對齊,寬沒對齊
int index_w = floor((dst_w - tmp_w) / 2.0);
std::cout << "index_w: " << index_w << std::endl;
for (int i = 0; i<dst_h; i++) {
memcpy(dst.data + i*dst_w + index_w, tmp.data + i*tmp_w, tmp_w);
}
effect_area.x = index_w;
effect_area.y = 0;
effect_area.width = tmp_w;
effect_area.height = tmp_h;
}
else if (tmp_h != dst_h) { //寬對齊, 高沒有對齊
int index_h = floor((dst_h - tmp_h) / 2.0);
std::cout << "index_h: " << index_h << std::endl;
memcpy(dst.data + index_h*dst_w, tmp.data, tmp_w*tmp_h);
effect_area.x = 0;
effect_area.y = index_h;
effect_area.width = tmp_w;
effect_area.height = tmp_h;
}
else {
printf("error\n");
}
return 0;
}
void main()
{
....
//OriMat 爲圖一的mat格式數據
int nSmallWidth = width / 4.0*3.0;
int nSmallHeight = height / 4.0*3.0;
Mat dst;
object_rect res_area;
(void)resize_uniform(OriMat, dst, Size(nSmallWidth, nSmallHeight), res_area);
SmallSlicebwMatrix.resize(nSmallHeight, nSmallWidth);//習慣使用eigen出來矩陣,所以轉換成
// eigen 格式的矩陣
cv2eigen(dst, SmallSlicebwMatrix);
OriSlicebwMatrix.setOnes();
int nWidthBeg = (width - nSmallWidth)*1.0 / 2.0;
int nHeightBeg = (height - nSmallHeight)*1.0 / 2.0;
for (int i = 0; i < nSmallHeight; i++)
{
for (int j = 0; j < nSmallWidth; j++)
{
OriSlicebwMatrix(i + nHeightBeg, j + nWidthBeg) = SmallSlicebwMatrix(i, j);
//OriSlicebwMatrix 即爲圖2
}
}
}