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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章