繁体   English   中英

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

[英]Create a circular masked image then place it on another image in OpenCV

如何为 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/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()

面具:

在此处输入图像描述

结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM