<pre><code>import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
</code></pre>
<p>在这一点上,你有一个颜色和一个灰色的图像。我们在这里处理<code>8-bit</code>,<code>uint8</code>图像。这意味着图像的像素值可以在<code>[0, 255]</code>的范围内,并且值必须是整数。</p>
<p><a href="https://i.stack.imgur.com/Bxl8h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bxl8h.jpg" alt="left-color,right-gray"/></a></p>
<p>让我们做一个二值阈值运算。它创建一个黑白蒙面图像。黑色区域有<code>0</code>值,白色区域有<code>255</code>值</p>
<pre><code>_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
</code></pre>
<p>下面左边可以看到面具。右边的图像是在灰度图像和遮罩之间应用<code>bitwise_and</code>操作的结果。结果是,遮罩的像素值为零(黑色)的空间位置在结果图像中变成了像素值为零。遮罩的像素值为255(白色)的位置,生成的图像保留其原始灰度值。</p>
<p><a href="https://i.stack.imgur.com/iw2XS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iw2XS.jpg" alt="left-mask,right-bitwise_and_with_mask"/></a></p>
<p>要将此蒙版应用于原始彩色图像,我们需要将蒙版转换为3通道图像,因为原始彩色图像是3通道图像。</p>
<pre><code>mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
</code></pre>
<p>然后,我们可以使用相同的<code>bitwise_and</code>函数将此蒙版应用到原始彩色图像。</p>
<pre><code>im_thresh_color = cv.bitwise_and(im_color, mask3)
</code></pre>
<p>代码中的<code>mask3</code>是左边下面的图像,而<code>im_thresh_color</code>在右边。</p>
<p><a href="https://i.stack.imgur.com/McuI7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/McuI7.jpg" alt="left-mask-3channel,right-bitwise_and_with_3channel-mask"/></a></p>
<p>你可以画出结果,自己看。</p>
<pre><code>cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
</code></pre>
<p>原始图像是<code>lenacolor.png</code>,我找到了<a href="https://homepages.cae.wisc.edu/~ece533/images/" rel="nofollow noreferrer">here</a>。</p>