如何在OpenCV中将温度数组转换为自定义规则的RGB数组
实现方案
1. 正确初始化numpy格式的RGB数组
需明确三通道的维度结构与数据类型,320x240的温度数组对应输出的RGB图像维度为(240, 320, 3),数据类型采用uint8匹配0-255的RGB取值范围:
import numpy as np # 此处为示例温度数组,替换为你实际的320x240温度数组即可 temperatureArray = np.random.uniform(20, 45, size=(240, 320)) # 按要求用numpy.zeros初始化 imageArray = np.zeros((240, 320, 3), dtype=np.uint8)
2. 温度到RGB的映射实现
推荐用numpy布尔掩码的向量化操作,运算效率远高于逐元素循环:
# 自定义各温度区间对应的RGB值,可按需扩展 blueRGB = (0, 0, 128) greenRGB = (0, 255, 0) redRGB = (255, 0, 0) # 按区间匹配赋值 # 25<温度≤30赋值蓝色 mask_blue = (temperatureArray > 25) & (temperatureArray <= 30) imageArray[mask_blue] = blueRGB # 温度≤25赋值绿色 mask_green = temperatureArray <= 25 imageArray[mask_green] = greenRGB # 温度>30赋值红色 mask_red = temperatureArray > 30 imageArray[mask_red] = redRGB
如果你的映射规则非常复杂,必须用循环实现,可按如下方式操作,不要使用列表的append方法,直接对numpy数组按索引赋值即可:
blueRGBValue = (0,0,128) for h in range(temperatureArray.shape[0]): for w in range(temperatureArray.shape[1]): current_temp = temperatureArray[h][w] if current_temp > 25 and current_temp <=30: imageArray[h][w] = blueRGBValue # 其余自定义判断规则可在此补充
错误原因说明
之前无法正常赋值通常是两个问题导致:
- 初始化
imageArray时没有指定第三维度,仅生成了二维数组,无法存储三个通道的RGB值 - 误将python列表的
append方法用在numpy数组上,numpy数组不支持这种原地追加操作,直接按位置赋值即可
内容的提问来源于stack exchange,提问作者F M
相关产品推荐
相关产品推荐

