cv2.resize()报RuntimeError: expected backend CPU and dtype Double but got backend CPU and dtype Float

cv2.resize()可以用于对ndarray进行resize(根据源码,下采样推荐使用cv2.INTER_AREA)

target_down_sample = cv2.resize(target, (128, 128), interpolation=cv2.INTER_AREA)

我对target做了边界填充,添加了一些0,原来的代码是这样的

# 填充0使输入的1,2维大于size
def pad(raw, size=(256, 256)):
    h, w = raw.shape[:2]
    new_h, new_w = max(size[0], h), max(size[1], w)
    res = np.zeros((new_h, new_w)) if len(raw.shape) == 2 else np.zeros((new_h, new_w, 3))
    res[0:h, 0:w, ...] = raw
    return res

pad预处理之后进行下采样

target = pad(target)
target_down_sample = cv2.resize(target, (128, 128), interpolation=cv2.INTER_AREA)

发现原来不填充0时可以正常运行,用pad填充以后报了错误

RuntimeError: expected backend CPU and dtype Double but got backend CPU and dtype Float

看了下感觉它的意思是,数据类型不对,希望得到double的,但是却得到float,debug了一下,发现类型确实从ndarray中元素的dtypepad前的float32变为pad后的float64了。将pad中创建np.zeros()添加了dtype与原来的一致,改为如下,报错消失:

def pad(raw, size=(256, 256)):
    h, w = raw.shape[:2]
    new_h, new_w = max(size[0], h), max(size[1], w)
    # add dtype=raw.dtype
    res = np.zeros((new_h, new_w), dtype=raw.dtype) if len(raw.shape) == 2 else np.zeros((new_h, new_w, 3), dtype=raw.dtype)
    res[0:h, 0:w, ...] = raw
    return res

你可能感兴趣的:(opencv,基础编程知识)