python - 如何将蒙版应用于 16 位图像?

标签 python opencv

apply mask like this to an image

如何将蒙版应用于 16 位图像?它适用于使用以下代码的 8 位图像:

image = misc.imread('test.jpg')
gray = cv2.cvtColor(image, cv2.Color(image, cv2.COLOR_BGR2GRAY)
x = 610
y = 220
w = h = 150
mask = np.zeros(gray.shape[:2], np.uint8)
mask[y:y+h,x:x+w] = 255
res = cv2.bitwise_and(gray, gray, mask = mask)
cv2.imshow("res", res)
cv2.waitKey(0)

但是当我尝试使用 16 bit.png 图片时它不起作用。我试过这段代码:
mask = np.zeros(gray.shape[:2], np.uint16)
mask[y:y+h, x:x+w] = 6535
res = cv2.bitwise_and(gray, gray, mask = mask)

我得到错误:

res = cv2.bitwise_and(gray, gray, mask = mask) cv2.error: /home/... : error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function binary_op



有人知道我如何将蒙版应用于我的 16 位图像吗?

最佳答案

根据OpenCV documentation , mask需要为 8 位:

mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.



错误消息似乎反射(reflect)了这一点,

res = cv2.bitwise_and(gray, gray, mask = mask) cv2.error: /home/... : error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function binary_op



因为它告诉您掩码的日期类型需要是 8 位无符号或 8 位有符号(整数)。

所以你的面具的定义需要是
mask = np.zeros(gray.shape[:2], np.uint8)
mask[y:y+h,x:x+w] = 255

就像之前一样。

关于python - 如何将蒙版应用于 16 位图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861126/

相关文章:

python - Django NoReverseMatch : trying to get slug in a template

Python Mysqldb游标没有属性 'fetchAll'

python - 生成事件时超出 tkinter 最大递归深度

c# - 在 OpenCV 与 C# 位图中读取 jpg 文件

java - 直方图比较

xcode - OS X Mavericks 中 Xcode 5 中架构 x86_64 错误的 undefined symbol

python - 如何将 .pyc 文件转换为 .exe 文件

python - 如何在 Python 中连接固定字符串和变量

python - 捕获 RTP 时间戳

python - 将灰色背景转换为白色背景而不干扰原始图像