【问题标题】:Create a circular masked image then place it on another image in OpenCV创建一个圆形蒙版图像,然后将其放置在 OpenCV 中的另一个图像上
【发布时间】:2021-08-10 20:54:52
【问题描述】:

如何在 Python 中为图像添加圆形遮罩,然后将该图像放在具有纯色背景的第二张图像上。

代码:

import cv2
import requests as rq

r = rq.get(url, stream=True) # get image from url

if r.status_code == 200:
    resp = r.raw
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)

【问题讨论】:

标签: python image opencv image-processing python-requests


【解决方案1】:

这是在 Python/OpenCV 中执行此操作的一种方法。

输入:

import cv2
import numpy as np

# read image
img = cv2.imread('lena.png')
ht, wd = img.shape[:2]

# define circle
radius = min(ht,wd)//2
xc = yc = radius

# draw filled circle in white on black background as mask
mask = np.zeros((ht,wd), dtype=np.uint8)
mask = cv2.circle(mask, (xc,yc), radius, 255, -1)

# create blue colored background
color = np.full_like(img, (255,0,0))

# apply mask to image
masked_img = cv2.bitwise_and(img, img, mask=mask)

# apply inverse mask to colored image
masked_color = cv2.bitwise_and(color, color, mask=255-mask)

# combine the two masked images
result = cv2.add(masked_img, masked_color)

# save results
cv2.imwrite('lena_circle_mask.png', mask)
cv2.imwrite('lena_circled.png', result)

cv2.imshow('image', img)
cv2.imshow('mask', mask)
cv2.imshow('masked image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

面具:

结果:

【讨论】:

  • 我怎么能做同样的事情,但我的蒙版图像是一个圆形,而不是像你的例子中那样有一个洞的正方形?
  • 发布您的确切面具和图像。
  • 没关系,我想完全按照您在示例中所做的操作,但使用透明背景。
  • 把我的圆形蒙版放到图片的 alpha 通道中。
猜你喜欢
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多