import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
此时你有一个彩色和一个灰色的图像。我们在这里处理8-bit、uint8 图像。这意味着图像可以具有[0, 255] 范围内的像素值,并且值必须是整数。
让我们做一个二元阈值操作。它创建一个黑白蒙版图像。黑色区域的值为0,白色区域的值为255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
可以在左下方看到面具。右边的图像是在灰度图像和蒙版之间应用bitwise_and 操作的结果。发生的情况是,掩码的像素值为零(黑色)的空间位置在结果图像中变为像素值为零。蒙版像素值为 255(白色)的位置,生成的图像保留其原始灰度值。
要将此蒙版应用于我们的原始彩色图像,我们需要将蒙版转换为 3 通道图像,因为原始彩色图像是 3 通道图像。
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
然后,我们可以使用相同的bitwise_and 函数将这个 3 通道蒙版应用于我们的彩色图像。
im_thresh_color = cv.bitwise_and(im_color, mask3)
代码中的mask3是左下图,im_thresh_color是右图。
您可以绘制结果并亲自查看。
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)
原图是lenacolor.png,我发现here。