ValueError: some of the strides of a given numpy array are negative.的解决方法

错误代码:
使用opencv读取图片后,转换颜色通道,再转为tensor

img = img[:, :, ::-1]   # BGR --> RGB
transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize([0.4948052, 0.48568845, 0.44682974], [0.24580306, 0.24236229, 0.2603115])
    ])    
img = transform(img)

报错原因:
数组经过行上的切片操作,会改变数组的连续性。关于连续性的内容,知乎上一篇文章很详细。

解决办法:

方法一:复制一份img保存到新的地址
img = img[:, :, ::-1]改为img = img[:, :, ::-1].copy()

方法二:将原有的img改为连续的
img = img[:, :, ::-1]下一行插入img = np.ascontiguousarray(img)

方法三:直接将原来的numpy.ndarray转为PIL Image格式
img = img[:, :, ::-1]下一行插入img = Image.fromarray(np.uint8(img))

参考链接:
https://blog.csdn.net/u011622208/article/details/89707828
https://blog.csdn.net/e01528/article/details/86067489

你可能感兴趣的:(玩转代码)