gpt4 book ai didi

python - 如何根据 python 中的自定义蒙版裁剪图像?

转载 作者:行者123 更新时间:2023-12-02 16:59:27 26 4
gpt4 key购买 nike

下面我附上了两张图片。我希望根据蒙版图像(第二张图像)将第一张图像裁剪成心形。

我搜索了解决方案,但无法找到执行此操作的简单方法。请帮助我解决问题。

2 张图片:

  1. 要裁剪的图像: enter image description here

  2. 蒙版图片:

enter image description here

最佳答案

让我们从从 sklearn 加载 temple 图像开始:

from sklearn.datasets import load_sample_images

dataset = load_sample_images()
temple = dataset.images[0]
plt.imshow(temple)

enter image description here

由于我们需要使用第二张图像作为掩码,因此我们必须进行二值阈值操作。这将创建一个黑白蒙版图像,然后我们可以使用它来蒙版之前的图像。

from matplotlib.pyplot import imread

heart = imread(r'path_to_im\heart.jpg', cv2.IMREAD_GRAYSCALE)
_, mask = cv2.threshold(heart, thresh=180, maxval=255, type=cv2.THRESH_BINARY)

我们现在可以修剪图像,使其尺寸与寺庙图像兼容:

temple_x, temple_y, _ = temple.shape
heart_x, heart_y = mask.shape

x_heart = min(temple_x, heart_x)
x_half_heart = mask.shape[0]//2

heart_mask = mask[x_half_heart-x_heart//2 : x_half_heart+x_heart//2+1, :temple_y]
plt.imshow(heart_mask, cmap='Greys_r')

enter image description here

现在我们必须对要 mask 的图像进行切片,以适应实际 mask 的尺寸。另一种形状是调整 mask 的大小,这是可行的,但我们最终会得到一个扭曲的心脏图像。要敷面膜,我们有 cv2.bitwise_and :

temple_width_half = temple.shape[1]//2
temple_to_mask = temple[:,temple_width_half-x_half_heart:temple_width_half+x_half_heart]
masked = cv2.bitwise_and(temple_to_mask,temple_to_mask,mask = heart_mask)
plt.imshow(masked)

enter image description here

如果您想改为使蒙版(黑色)区域透明:

tmp = cv2.cvtColor(masked, cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
b, g, r = cv2.split(masked)
rgba = [b,g,r, alpha]
masked_tr = cv2.merge(rgba,4)

plt.axis('off')
plt.imshow(dst)

enter image description here

关于python - 如何根据 python 中的自定义蒙版裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62813546/

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