<p>好吧,如果你想让背景不是纯黑色,这里有一个解决方案。我们只需要反转遮罩并将其应用于大小相同的背景图像中,然后将背景和前景结合起来。这个解决方案的一个优点是背景可以是任何东西(甚至是其他图像)。</p>
<p>此示例是从<a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html" rel="noreferrer">Hough Circle Transform</a>修改的。第一个图像是OpenCV徽标,第二个是原始遮罩,第三个是背景+前景的组合。</p>
<p><a href="https://i.stack.imgur.com/vqQw2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vqQw2.png" alt="apply mask and get a customized background"/></a></p>
<pre><code># http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np
# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) # mask is only
for i in circles[0, :]:
cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)
# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)
# combine foreground+background
final = cv2.bitwise_or(fg, bk)
</code></pre>
<p><em>注意:最好使用opencv方法,因为它们是经过优化的。</em></p>