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

标签 opencv ionic-framework image-processing

我正在使用 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/

相关文章:

opencv - 使用Opencv从相机获取部分图像

angularjs - 混合应用程序 IFRAME youtube 嵌入不起作用

angular - 在ionic 4中动态选择单选按钮

android - 在 Renderscript Compute 中将数组传递给 rsForEach

python - 从图像中重叠的字母中提取数据

python - 如何在Python中使用OpenCV在检测部分绘制矩形?

python - OpenCV中的img.copy(),img.shape()

android - 如何将 OpenCV 库添加到 AS3.1.2 和 NDK 17.0

javascript - 按钮不能工作

android - 使用 OpenCV 分析蛋白质凝胶的数据