You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用bitwise_and后输出黑图,如何定义掩码保留图像头部区域?

问题:OpenCV bitwise_and输出黑色图像,如何正确定义掩码?

目标图像

需求:仅保留图像中的头部区域,移除其余部分,但运行以下代码后输出全黑图像:

import cv2
import matplotlib.pyplot as plt
import numpy as np
image1 =cv2.imread("ML.png")
image1 =cv2.resize(image1,(400,400))
print(image1)
mask =np.zeros((400,400,3),dtype='uint8')
mask[0:50,0:120]=1
mask[70:180,130:320] =1
mask[150:240,190:390] =1
print(mask)
image1_changed =cv2.bitwise_and(image1,mask)
print(image1_changed)
plt.imshow(np.uint8(image1_changed))
plt.show()

相关矩阵输出:

# 原图像像素矩阵
[[[255 250 245]
  [255 250 245]
  [255 250 245]
  ...
  [255 250 245]
  [255 250 245]
  [255 250 245]]

 ...

 [[255 250 245]
  [255 250 245]
  [255 250 245]
  ...
  [255 250 245]
  [255 250 245]
  [255 250 245]]]

# 掩码矩阵
[[[1 1 1]
  [1 1 1]
  [1 1 1]
  ...
  [0 0 0]
  [0 0 0]
  [0 0 0]]

 ...

 [[0 0 0]
  [0 0 0]
  [0 0 0]
  ...
  [0 0 0]
  [0 0 0]
  [0 0 0]]]

# 运算后结果矩阵
[[[1 0 1]
  [1 0 1]
  [1 0 1]
  ...
  [0 0 0]
  [0 0 0]
  [0 0 0]]

 ...

 [[0 0 0]
  [0 0 0]
  [0 0 0]
  ...
  [0 0 0]
  [0 0 0]
  [0 0 0]]]

问题原因与解决方法

问题根源

  1. 掩码值错误:你设置掩码区域为1,但图像像素是0-255的uint8类型。按位与操作中,1(二进制00000001)和图像像素(比如250是11111010)按位与结果是0,所以输出全黑。
  2. 掩码通道冗余:OpenCV的bitwise_and支持单通道掩码,不需要和图像一样设置为3通道,浪费内存。
  3. 颜色空间不匹配:OpenCV读入的图像是BGR格式,直接用matplotlib显示会颜色失真,也可能导致视觉上误判为全黑。

修正后的代码

import cv2
import matplotlib.pyplot as plt
import numpy as np

# 读取图像并调整大小
image1 = cv2.imread("ML.png")
image1 = cv2.resize(image1, (400, 400))
# 转换为RGB格式适配matplotlib显示
image_rgb = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)

# 创建单通道掩码,初始全黑
mask = np.zeros((400, 400), dtype='uint8')
# 将头部区域设置为255(全白),请根据实际图像调整坐标
mask[50:200, 100:300] = 255

# 执行按位与操作,第三个参数传入单通道掩码
image1_changed = cv2.bitwise_and(image_rgb, image_rgb, mask=mask)

# 显示结果
plt.imshow(image1_changed)
plt.show()

关键说明

  • 掩码中需要保留的区域必须设为255(二进制全1),这样和原图像像素按位与后,原像素值会完整保留。
  • 使用单通道掩码即可,bitwise_and的第三个参数专门用于接收掩码,无需和输入图像同通道。
  • 必须将OpenCV的BGR图像转换为RGB后再用matplotlib显示,避免颜色异常。

内容的提问来源于stack exchange,提问作者user4356954

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:44:54