如何在图像中创建透明形状

How to create a transparent shape in the image

我现在有一张图片,我想在图片中创建一个透明形状,以便我可以在该形状中放置另一张图片。

我想实现这样的目标

有没有办法在 java 或 python 中以编程方式执行此操作?如果不是我如何手动执行此操作。

我有 linux 环境和一些图像编辑器,但我什至无法手动执行此操作。

来自 here

# import the necessary packages
from __future__ import print_function
import numpy as np
import cv2

# load the image
image = cv2.imread("pic.jpg")

# loop over the alpha transparency values
for alpha in np.arange(0, 1.1, 0.1)[::-1]:
    # create two copies of the original image -- one for
    # the overlay and one for the final output image
    overlay = image.copy()
    output = image.copy()

    # draw a red rectangle surrounding Adrian in the image
    # along with the text "PyImageSearch" at the top-left
    # corner
    cv2.rectangle(overlay, (420, 205), (595, 385),
        (0, 0, 255), -1)
    cv2.putText(overlay, "PyImageSearch: alpha={}".format(alpha),
        (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
# apply the overlay
    cv2.addWeighted(overlay, alpha, output, 1 - alpha,
        0, output)
# show the output image
    print("alpha={}, beta={}".format(alpha, 1 - alpha))
    cv2.imshow("Output", output)
    cv2.waitKey(0)

所以,下面利用了:

所以,从这个开始...

我想在它后面加上这个(但是偷看)

我们需要做的第一件事是为我们想要变得透明的区域制作一个基于“alpha”的蒙版。为此,我使用了 RadialGradientPaint,因为它允许我在边缘周围产生“淡化”效果。

现在,我已经完成了所有的数学计算(使用一个简单的图像编辑器来计算),所以我知道我希望“洞”出现在哪里

BufferedImage city = ImageIO.read(new File("/Users/swhitehead/Downloads/City.jpg"));

BufferedImage mask = new BufferedImage(city.getWidth(), city.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g2d = mask.createGraphics();
Color transparent = new Color(255, 0, 0, 0);
Color fill = Color.RED;
RadialGradientPaint rgp = new RadialGradientPaint(
                new Point2D.Double(955, 185),
                185,
                new float[]{0f, 0.75f, 1f},
                new Color[]{transparent, transparent, fill});
g2d.setPaint(rgp);
g2d.fill(new Rectangle(0, 0, mask.getWidth(), mask.getHeight()));
g2d.dispose();

接下来,我们使用 AlphaComposite 在原始(城市)图像上绘制蒙版...

BufferedImage masked = new BufferedImage(city.getWidth(), city.getHeight(), BufferedImage.TYPE_INT_ARGB);
g2d = masked.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, masked.getWidth(), masked.getHeight());
g2d.drawImage(city, 0, 0, null);
g2d.setComposite(AlphaComposite.DstAtop);
g2d.drawImage(mask, 0, 0, null);
g2d.dispose();

这会生成类似于...

“白”洞其实是透明的,只是页面也是白的:/

最后,我们将 masked 图像与背景图像组合...

BufferedImage composite = new BufferedImage(city.getWidth(), city.getHeight(), BufferedImage.TYPE_INT_ARGB);
g2d = composite.createGraphics();
g2d.drawImage(background, city.getWidth() - background.getWidth(), 0, null);
g2d.drawImage(masked, 0, 0, null);
g2d.dispose();

制作类似...

所以,根据您的描述,我认为这就是您的意思