这是在 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()
面具:
结果: