Python 创建一个圆形蒙版图像,然后将其放置在OpenCV中的另一个图像上

Python 创建一个圆形蒙版图像,然后将其放置在OpenCV中的另一个图像上,python,image,opencv,image-processing,python-requests,Python,Image,Opencv,Image Processing,Python Requests,我试图创建一个有坚实背景的图像,但中间有第二个圆形图像。第二个图像不是圆形的,所以我需要制作一个遮罩 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")

我试图创建一个有坚实背景的图像,但中间有第二个圆形图像。第二个图像不是圆形的,所以我需要制作一个遮罩

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/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()