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

16位图像直方图绘制及指定灰度区间灰度图像生成求助

解决方案

问题说明

cv.inRange() 函数返回的是二值掩码图像——符合区间条件的像素会被设为255(白色),不符合的设为0(黑色),这就是你得到黑白图的原因。要生成保留原灰度值的筛选图像,需要基于掩码保留区间内的像素灰度,将区间外的像素置为0(或其他指定值)。

方法一:Numpy布尔索引(简洁高效)

直接通过布尔条件筛选像素,保留目标区间的灰度值,其余置0:

import cv2 as cv
import numpy as np

# 读取16位深度的灰度图像
gray = cv.imread('1.tiff', cv.IMREAD_ANYDEPTH)

# 定义目标灰度区间
lower_bound = 34000
upper_bound = 36000

# 生成布尔掩码:标记区间内的像素
mask = (gray >= lower_bound) & (gray <= upper_bound)
# 保留区间内的灰度值,其余像素设为0
gray_filtered = np.where(mask, gray, 0)

# 显示筛选后的图像
cv.imshow('Filtered 16-bit Grayscale', gray_filtered)
if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()

# 保存结果(保持16位深度)
cv.imwrite('filtered_16bit.tiff', gray_filtered)

方法二:OpenCV掩码结合位运算

先用cv.inRange()生成掩码,再通过位运算保留原灰度值:

import cv2 as cv

# 读取16位灰度图像
gray = cv.imread('1.tiff', cv.IMREAD_ANYDEPTH)

# 定义灰度区间
lower_bound = 34000
upper_bound = 36000

# 生成与图像深度匹配的掩码(16位)
mask = cv.inRange(gray, lower_bound, upper_bound)
# 位运算保留区间内的灰度值,其余置0
gray_filtered = cv.bitwise_and(gray, gray, mask=mask)

# 显示图像
cv.imshow('Filtered 16-bit Grayscale', gray_filtered)
if cv.waitKey(0) & 0xff == 27:
    cv.destroyAllWindows()

补充:直方图与筛选图像联动展示

如果需要同时查看直方图和筛选结果,可以用Matplotlib组合展示:

from skimage import io
import matplotlib.pyplot as plt
import numpy as np

image = io.imread('1.tiff')
lower = 34000
upper = 36000

# 创建画布
plt.figure(figsize=(14, 6))

# 绘制直方图并标记筛选区间
plt.subplot(1, 2, 1)
plt.hist(image.ravel(), bins=65536)
plt.xlabel('Intensity Value')
plt.ylabel('Pixel Count')
plt.title('16-bit Grayscale Histogram')
plt.axvspan(lower, upper, color='red', alpha=0.3, label='Filter Range')
plt.legend()

# 生成并显示筛选后的图像
mask = (image >= lower) & (image <= upper)
filtered_img = np.where(mask, image, 0)
plt.subplot(1, 2, 2)
plt.imshow(filtered_img, cmap='gray', vmin=0, vmax=65535)
plt.title('Filtered Image')
plt.axis('off')

plt.tight_layout()
plt.show()

注意事项

  • 16位图像在OpenCV窗口显示时,可能会因自动映射到8位导致视觉偏暗,可通过cv.normalize(gray_filtered, gray_filtered, 0, 65535, cv.NORM_MINMAX)归一化后再显示,或用Matplotlib的imshow指定vmin和vmax确保灰度范围正确映射。
  • 保存图像时,要确保使用支持16位深度的格式(如TIFF),避免丢失精度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:17:39