如何使用OpenCV Python遮挡圆以外的区域?

问题描述 投票:1回答:1

我有一个图像,我正在尝试使用opencv涂掉圆外的所有区域。

Source image

Goal image

python-3.x image opencv image-processing mask
1个回答
1
投票

这是Python / OpenCV中的一种方法。

  • 读取输入
  • 获取尺寸并除以2以使用中心和半径
  • [在黑色背景上创建一个填充的白色圆圈作为蒙版
  • 将蒙版应用于图像
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('jeep.jpg')
hh, ww = img.shape[:2]
hh2 = hh // 2
ww2 = ww // 2

# define circles
radius = hh2
xc = hh2
yc = ww2

# draw filled circle in white on black background as mask
mask = np.zeros_like(img)
mask = cv2.circle(mask, (xc,yc), radius, (255,255,255), -1)

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

# save results
cv2.imwrite('jeep_mask.png', mask)
cv2.imwrite('jeep_masked.png', result)

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

遮罩图像:

enter image description here

结果图像:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.