【问题标题】:Is there any way to rotate an image represented by a two-dimensional array of pixel values?有没有办法旋转由像素值的二维数组表示的图像?
【发布时间】:2021-11-16 01:12:45
【问题描述】:

我正在尝试将 Matlab 的 imrotate 函数的功能引入 Java。详细地说,由于我已将图像的像素值存储在 2d 数组中,因此我想以指定角度围绕其中心旋转该图像。我找到的大多数答案(使用 AffineTransform 和 Graphics2D 和 BufferedImage)都是面向图形的,我无法产生我需要的结果,因为我不需要在视觉上绘制它。例如下面的函数返回一个所有像素值为0的图像(我把可视化部分注释掉了)

public static BufferedImage rotateImage(BufferedImage img, double angle) {
        double rads = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads));
        int w = img.getWidth();
        int h = img.getHeight();
        int newWidth = (int) Math.floor(w * cos + h * sin);
        int newHeight = (int) Math.floor(h * cos + w * sin);

        BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();
        AffineTransform at = new AffineTransform();
        at.translate((newWidth - w) / 2, (newHeight - h) / 2);

        int x = w / 2;
        int y = h / 2;

        at.rotate(rads, x, y);
        g2d.setTransform(at);
//        g2d.drawImage(img, 0, 0, this);
//        g2d.setColor(Color.RED);
//        g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
//        g2d.dispose();

        return rotated;

非常感谢任何帮助或建议。另外,如果您需要更多详细信息,请告诉我。

更新:我认为我应该更好地澄清我的问题。 所以我有一个指纹图像,我需要从中提取一个子图像。之后,我必须根据提供的角度旋转子图像。我尝试过的是:首先,将图像作为 BufferedImage 加载。然后,我将子图像提取为二维整数数组。最后,我需要应用旋转。当我做了一些研究时,我知道这听起来很傻,我可能很傻,但我尝试用子图像的 2d 数组创建一个 BufferedImage,然后用那里给出的方法旋转。然而,我并没有成功。我期待听到你们的 cmets 关于我在概念上或程序上做错了什么。非常感谢。

【问题讨论】:

  • 这个答案可以帮助你stackoverflow.com/questions/54746463/… 吗?
  • 感谢您的建议。不幸的是,它对我不起作用,因为我的数据是一个二维整数数组。我还编辑了问题以使其更清晰。
  • 无论数据是整数、浮点数、颜色、公关,无论您想要什么,旋转都应该有效。我不明白为什么它在你的情况下不起作用。
  • @MauricioCeleLopezBelon 很抱歉造成混乱。我再次阅读了您的伪代码,发现它非常有用。不过我有一个问题:由于 Matlab 的 imrotate 的默认方法使用双线性插值。这会有很大的不同吗?
  • 是的,由于二维网格的离散特性,需要进行某种插值。差异可能非常明显。

标签: java arrays image matlab rotation


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 2021-10-01
  • 2019-08-22
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 2021-10-05
  • 2020-02-21
相关资源
最近更新 更多