gpt4 book ai didi

opencv - 在 OpenCV.js 中旋转时图像自动裁剪

转载 作者:行者123 更新时间:2023-12-01 05:52:07 24 4
gpt4 key购买 nike

我正在使用 OpenCV.js 向左和向右旋转图像,但是在旋转时它被裁剪了。
这是我的代码:

    let src = cv.imread('img');
let dst = new cv.Mat();
let dsize = new cv.Size(src.rows, src.cols);
let center = new cv.Point(src.cols/2, src.rows/2);
let M = cv.getRotationMatrix2D(center, 90, 1);
cv.warpAffine(src, dst, M, dsize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, new cv.Scalar());
cv.imshow('canvasOutput', dst);
src.delete(); dst.delete(); M.delete();

下面是一个例子:

这是我的源图片: source

这就是我想要的: image

但它是这样返回的: cropped

我应该怎么做才能解决这个问题?

P/s:除了javascript,我不知道如何使用不同的语言。

最佳答案

我也遇到了这个问题,所以查看了@fernando-garcia 的回答,但是我看不到 rotate已在 opencv.js 中实现,因此似乎@dan-mašek 帖子中的链接中的修复是解决此问题的最佳解决方案,但是所需的功能略有不同。

这是我想出的解决方案(注意,我还没有测试过这个确切的代码,可能有一种更优雅/有效的编写方式,但它给出了总体思路。此外,这只适用于由倍数旋转的图像90°):

const canvas = document.getElementById('canvas');
const image = cv.imread(canvas);
let output = new cv.Mat();
const size = new cv.Size();

size.width = image.cols;
size.height = image.rows;

// To add transparent borders
const scalar = new cv.Scalar(0, 0, 0, 0);

let center;
let padding;

if (height > width) {
center = new cv.Point(height / 2, height / 2);
padding = (height - width) / 2;
// Pad out the left and right before rotating to make the width the same as the height
cv.copyMakeBorder(image, output, 0, 0, padding, padding, cv.BORDER_CONSTANT, scalar);
size.width = height;
} else {
center = new cv.Point(width / 2, width / 2);
padding = (width - height) / 2;
// Pad out the top and bottom before rotating to make the height the same as the width
cv.copyMakeBorder(image, output, padding, padding, 0, 0, cv.BORDER_CONSTANT, scalar);
size.height = width;
}

// Do the rotation
const rotationMatrix = cv.getRotationMatrix2d(center, 90, 1);

cv.warpAffine(
output,
output,
rotationMatrix,
size,
cv.INTER_LINEAR,
cv.BORDER_CONSTANT,
new cv.Scalar()
);

let rectangle;

if (height > width) {
rectangle = new cv.Rect(0, padding, height, width);
} else {
/* These arguments might not be in the right order as my solution only needed height
* > width so I've just assumed this is the order they'll need to be for width >=
* height.
*/
rectangle = new cv.Rect(padding, 0, height, width);
}

// Crop the image back to its original dimensions
output = output.roi(rectangle);

cv.imshow(canvas, output);

关于opencv - 在 OpenCV.js 中旋转时图像自动裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52963949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com