如何在R语言中使用imager包为RGB图像应用二进制掩码
基于imager包的RGB图像二进制掩码应用方案
场景说明
已通过imager::load.image()加载RGB图像,使用imager::threshold()生成二进制掩码。单通道图像与掩码相乘可实现遮罩,但直接执行RGB_image * Mask会因维度不匹配失效(RGB图像为3通道,掩码为单通道)。
方案一:直接为RGB图像应用掩码
利用R的数组维度广播特性,将掩码扩展为与RGB图像一致的维度后再相乘:
# 扩展掩码维度,匹配RGB图像的通道数 mask_rgb <- array(Mask, dim = dim(RGB_image)) # 应用掩码 masked_rgb <- RGB_image * mask_rgb
或者使用imager包的map_il函数对每个通道批量处理:
masked_rgb <- map_il(RGB_image, ~ .x * Mask)
方案二:合并处理后的单通道为RGB图像
若已分别对红、绿、蓝通道应用掩码,可使用imager::RGB()函数直接合并:
# 拆分通道并应用掩码(原有代码) red_channel <- R(RGB_image) * Mask green_channel <- G(RGB_image) * Mask blue_channel <- B(RGB_image) * Mask # 合并为RGB图像 masked_rgb <- RGB(red_channel, green_channel, blue_channel)
也可通过数组重组的方式实现:
# 将三个通道数据重组为RGB图像维度 rgb_array <- array(c(red_channel, green_channel, blue_channel), dim = c(dim(red_channel)[1], dim(red_channel)[2], 1, 3)) masked_rgb <- as.cimg(rgb_array)
内容的提问来源于stack exchange,提问作者Rens
相关产品推荐
相关产品推荐

