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

时间:2018-06-05 10:55:33

标签: java python image-processing transparent

我现在有一个图像我想在图像中创建一个透明的形状,这样我就可以将另一个图像放在那个形状中。

我想实现类似的目标

enter image description here

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

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

2 个答案:

答案 0 :(得分:1)

因此,以下内容使用:

所以,从这开始...

Foreground

我想在它后面添加它(但是偷看)

Peek-a-Boo

我们需要做的第一件事是为我们想要变得透明的区域制作一个基于“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

“白色”洞实际上是透明的,它只是页面也是白色的:/

最后,我们将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();

产生类似......

的东西

He's always watching

所以,根据你的描述,这就是我所说的你的意思

答案 1 :(得分:0)

来自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)