gpt4 book ai didi

java - 如何从形状中减去图像的面积

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:04 24 4
gpt4 key购买 nike

这里的基本问题是我绘制了一个灰度图像,并且是形状的矩形边界。我已经在该矩形上绘制了形状。现在我需要从图像中删除访问区域。

从形状获取矩形边界的代码是:

public static Rectangle getBoundingBox(Shape shape,Graphics2D g) {
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;

final Rectangle polygonBounds = shape.getBounds();

int ax = polygonBounds.x;
int ay = polygonBounds.y;
int bx = ax + polygonBounds.width;
int by = ay + polygonBounds.height;

minX = Math.min(ax, minX);
minY = Math.min(ay, minY);
maxX = Math.max(bx, maxX);
maxY = Math.max(by, maxY);


final Rectangle boundingBox = new Rectangle(minX, minY, 1, 1);
boundingBox.add(maxX, maxY);
return boundingBox;
}

绘制矩形和所选形状的代码是:

        Rectangle rect = getBoundingBox((Shape)selectedArea,g);
int x = (int)rect.getX();
int y = (int)rect.getY();
int width = (int)rect.getWidth();
int height = (int)rect.getHeight();
if((x+width)>grayScaledImage.getWidth()){
width = grayScaledImage.getWidth()-x;
}
if(((y+height)>grayScaledImage.getHeight())){
height = grayScaledImage.getHeight()-y;
}

BufferedImage img = grayScaledImage.getSubimage(x,y,width,height);
}
}
}

g.drawImage(img,x,y,null);

对矩形内的图像进行灰度化的代码是:

       private BufferedImage toGray(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Color c = new Color(image.getRGB(j, i));
int red = (int) (c.getRed() * 0.3);
int green = (int) (c.getGreen() * 0.59);
int blue = (int) (c.getBlue() * 0.11);

int sum = red + green + blue;
Color newColor = new Color(sum, sum, sum);
//Color newColor =Color.red;
image.setRGB(j, i, newColor.getRGB());
}
}
return image;
}

我已经尝试过 setClip() 方法,但它有某种抗锯齿问题。因此,如果能获得一些帮助那就太好了。

图像是:

enter image description here

需要从图像中减去浅灰度部分。

所需的图像是:

enter image description here

多边形可以是任何形状。

最佳答案

这里我建议你尝试一下这种方法:您可以创建一个Polygon对象并给出xPointsyPoint。像这样的事情

int[] xPoints;
int[] yPoints;
int length = xPoint.length;
Polygon polygon = new Polygon(xPoints, yPoints, length );

现在添加颜色,如下所示:

Rectangle bounds = polygon.getBounds();
for (int i = 0; i < bounds.width; i++) {
for (int j = 0; j < bounds.height; j++) {
if (polygon.contains(i, j)) {// check if the point is inside the polygon
// do the color stuff here
Color c = new Color(image.getRGB(j, i));
int red = (int) (c.getRed() * 0.3);
int green = (int) (c.getGreen() * 0.59);
int blue = (int) (c.getBlue() * 0.11);

int sum = red + green + blue;
Color newColor = new Color(sum, sum, sum);
//Color newColor =Color.red;
image.setRGB(j, i, newColor.getRGB());
}
}
}

就是这样(没有任何额外的过程)

关于java - 如何从形状中减去图像的面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42248908/

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