gpt4 book ai didi

Java OpenCV 将小图像分层到具有透明度的大图像上

转载 作者:行者123 更新时间:2023-12-02 12:14:50 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,将一个图像覆盖在另一个图像之上的具有透明度的矩形上,但是它不会对图像进行分层,它只是删除了我覆盖的部分,并且透明度穿过整个图像。这是我的代码。

public static void overlayImage(String imagePath, String overlayPath, int x, int y, int width, int height) {
Mat overlay = Imgcodecs.imread(overlayPath, Imgcodecs.IMREAD_UNCHANGED);
Mat image = Imgcodecs.imread(imagePath, Imgcodecs.IMREAD_UNCHANGED);

Rectangle rect = new Rectangle(x, y, width, height);
Imgproc.resize(overlay, overlay, rect.size());
Mat submat = image.submat(new Rect(rect.x, rect.y, overlay.cols(), overlay.rows()));
overlay.copyTo(submat);
Imgcodecs.imwrite(imagePath, image);
}

编辑:以下是一些示例图片:之前:

enter image description here

之后:

enter image description here

最佳答案

发现这个函数完全符合我的需要。

 public static void overlayImage(Mat background,Mat foreground,Mat output, Point location){

background.copyTo(output);

for(int y = (int) Math.max(location.y , 0); y < background.rows(); ++y){

int fY = (int) (y - location.y);

if(fY >= foreground.rows())
break;

for(int x = (int) Math.max(location.x, 0); x < background.cols(); ++x){
int fX = (int) (x - location.x);
if(fX >= foreground.cols()){
break;
}

double opacity;
double[] finalPixelValue = new double[4];

opacity = foreground.get(fY , fX)[3];

finalPixelValue[0] = background.get(y, x)[0];
finalPixelValue[1] = background.get(y, x)[1];
finalPixelValue[2] = background.get(y, x)[2];
finalPixelValue[3] = background.get(y, x)[3];

for(int c = 0; c < output.channels(); ++c){
if(opacity > 0){
double foregroundPx = foreground.get(fY, fX)[c];
double backgroundPx = background.get(y, x)[c];

float fOpacity = (float) (opacity / 255);
finalPixelValue[c] = ((backgroundPx * ( 1.0 - fOpacity)) + (foregroundPx * fOpacity));
if(c==3){
finalPixelValue[c] = foreground.get(fY,fX)[3];
}
}
}
output.put(y, x,finalPixelValue);
}
}
}

关于Java OpenCV 将小图像分层到具有透明度的大图像上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46265726/

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