Python中1D Bayer数据数组拆分与合并的最优实现方法
优化1D Bayer数组拆分与合并的矢量化实现
任务1:快速拆分Bayer数组为4个颜色平面
你的现有代码依赖Python循环,这是速度瓶颈的核心原因。Numpy的矢量化操作(无需Python层面循环)能大幅提升效率,完全匹配你的拆分规则:
优化实现代码
import numpy as np from numpy import ndarray def splitVectorToColorPlanes_fast(cfa: ndarray, imageHeight: int, imageWidth: int) -> ndarray: # 将1D数组重塑为2D图像矩阵 cfa_matrix = cfa.reshape((imageHeight, imageWidth)) # 利用numpy切片直接提取四个颜色平面,无需循环 plane0 = cfa_matrix[::2, ::2].ravel() # 偶数行、偶数列 plane1 = cfa_matrix[::2, 1::2].ravel() # 偶数行、奇数列 plane2 = cfa_matrix[1::2, ::2].ravel() # 奇数行、偶数列 plane3 = cfa_matrix[1::2, 1::2].ravel()# 奇数行、奇数列 # 堆叠四个平面为最终输出 return np.stack([plane0, plane1, plane2, plane3])
原理说明
::2步长切片直接选取目标行/列,一次性提取所有对应元素ravel()将2D切片结果拉平为1D数组,严格保持原始顺序- 整个过程基于Numpy的C底层实现,比Python循环快数倍甚至数十倍
任务2:反向合并4个颜色平面为1D Bayer数组
同样用矢量化操作实现反向逻辑,彻底避免循环:
优化实现代码
def mergeColorPlanesToVector_fast(colorPlanes: ndarray, imageHeight: int, imageWidth: int) -> ndarray: h_half = imageHeight // 2 w_half = imageWidth // 2 # 将每个颜色平面重塑为(h/2, w/2)的矩阵 plane0 = colorPlanes[0].reshape(h_half, w_half) plane1 = colorPlanes[1].reshape(h_half, w_half) plane2 = colorPlanes[2].reshape(h_half, w_half) plane3 = colorPlanes[3].reshape(h_half, w_half) # 构建偶数行:plane0和plane1元素按列交替排列(如[0,1,0,1...]) even_rows = np.stack([plane0, plane1], axis=2).reshape(h_half, imageWidth) # 构建奇数行:plane2和plane3元素按列交替排列(如[2,3,2,3...]) odd_rows = np.stack([plane2, plane3], axis=2).reshape(h_half, imageWidth) # 合并偶数行和奇数行,恢复原始图像矩阵结构 full_matrix = np.empty((imageHeight, imageWidth), dtype=colorPlanes.dtype) full_matrix[::2] = even_rows full_matrix[1::2] = odd_rows # 拉平为1D数组 return full_matrix.ravel()
原理说明
np.stack([plane0, plane1], axis=2)在第三个维度堆叠两个平面,形成(h/2, w/2, 2)的矩阵reshape(h_half, imageWidth)将堆叠后的矩阵直接转为(h/2, w)的行,实现元素交替排列- 最后通过切片合并奇偶行,恢复原始结构后拉平为1D数组
关于现成库的说明
不需要额外第三方库,Numpy本身就提供了足够高效的工具。上述实现完全基于Numpy核心操作,底层是优化的C代码,已经是此类数组操作的最快方式之一。
内容的提问来源于stack exchange,提问作者Oleksii Matiash
相关产品推荐
相关产品推荐

