最近遇到的一个pytorch报错:

然后报错了,这个几行代码就是从一个图片中读入数据,把bgr模式图片矩阵转换为rgb模式,这里采用的是改变矩阵索引,索引倒排     [..., ::-1]   。

看了这个报错有些懵,因为确实没想明白这么简单的操作都会报错。

后来查了查有些搞明白了,就是pytorch框架通过numpy的array对象生成tensor时要求传入的numpy的array对象是内存连续的。

如上述:

img = cv2.imread(r"timg.jpg")    得到一个内存连续的array 对象,但是

img = cv2.imread(r"timg.jpg")[...,::-1]  
这时将得到的连续的array对象的最后一维索引倒排了,
这样的话倒排索引得到的array对象如果按照倒排后的索引来看就是内存不连续的,
这样传入pytorch中就会报错了。

这里的解决方法就是传入一个内存连续的array对象。

方法1.

import numpy as np
import torch
# 对彩色图片RGB 进行像素点的kmeans聚类
import cv2 img = cv2.imread(r"timg.jpg")[..., ::-1]
img2 = np.ascontiguousarray(img)
data = torch.from_numpy(img2).float() img[...]=0
print(img)
print(img2)

       

可以看到 调用

np.ascontiguousarray   

我们得到的一个新的内存连续的array,  新旧array不共享内存。

方法2.  同理

import numpy as np
import torch
# 对彩色图片RGB 进行像素点的kmeans聚类
import cv2 img = cv2.imread(r"timg.jpg")[..., ::-1].copy()
data = torch.from_numpy(img).float()

直接对倒排索引的array对象进行 copy 操作,这样得到不共享内存的新的array对象, 新生成的array对象自然是内存连续的。

----------------------------------------------------------------------

为什么  pytorch 要求传入的numpy的array对象必须是内存连续的呢?

可以看:

https://blog.csdn.net/zz2230633069/article/details/93170271

https://zhuanlan.zhihu.com/p/59767914

https://www.cnblogs.com/peixu/articles/13455350.html

大致意思就是说内存连续的array或tensor对象在进行矩阵运算时速度更快。

-------------------------------------------------------------

参考:

https://blog.csdn.net/e01528/article/details/86067489

https://blog.csdn.net/qq_36891953/article/details/95482539

https://blog.csdn.net/u011622208/article/details/89707828

pytorch报错----------- ***ValueError: some of the strides of a given numpy array are negative.的更多相关文章

  1. pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1,512,1,1])

    1.pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.S ...

  2. keras 报错 ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("embedding_1/random_uniform:0", shape=(5001, 128), dtype=float32)'

    在服务器上训练并保存模型,复制到本地之后load_model()报错: ValueError: Tensor conversion requested dtype int32 for Tensor w ...

  3. matplotlib.pyplot import报错: ValueError: _getfullpathname: embedded null character in path

    Environment: Windows 10, Anaconda 3.6 matplotlib 2.0 import matplotlib.pyplot 报错: ValueError: _getfu ...

  4. dbfread报错ValueError错误解决方法

    问题 我在用dbfread处理.dbf数据的时候出现了报错 ValueError("could not convert string to float: b'.'",) 然后查找. ...

  5. Pytorch报错:cuda runtime error (59) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorMath.cu:26

    Pytorch报错:cuda runtime error (59) : device-side assert triggered at /pytorch/aten/src/THC/generic/TH ...

  6. Anaconda 安装 pytorch报错解决方法

    一.安装Pytorch: # -c 指定用pytorch镜像源下载软件conda install pytorch torchvision cpuonly -c pytorch 报错: 二.配置: ch ...

  7. moviepy音视频剪辑VideoClip类fl_image方法image_func报错ValueError: assignment destination is read-only解决办法

    ☞ ░ 前往老猿Python博文目录 ░ moviepy音视频剪辑模块的视频剪辑基类VideoClip的fl_image方法用于进行对剪辑帧数据进行变换. 调用语法:fl_image(self, im ...

  8. tensorflow-TFRecord报错ValueError: Protocol message Feature has no "feature" field.

    编写代码用TFRecord数据结构存储数据集信息是报错:ValueError: Protocol message Feature has no "feature" field.或和 ...

  9. Pytorch 报错总结

    目前在学习pytorch,自己写了一些例子,在这里记录下来一些报错及总结 1. RuntimeError: Expected object of type torch.FloatTensor but ...

  10. datetime.strptime格式转换报错ValueError

    今天遇到一个报错:ValueError: time data '2018-10-10(Wednesday) AM0:50' does not match format '%Y-%m-%d(%A) %p ...

随机推荐

  1. OpenSpeedTest-Server局域网速度测试服务程序

    OpenSpeedTest-Server局域网速度测试服务程序,局域网测速.

  2. 搜狗五笔 date 自定义时间格式

    搜狗五笔 date 自定义时间格式 搜狗五笔 date 默认打出的是"2023-6-15",如果需要"2023-06-15",则需要在自定义短语中设置 属性设置 ...

  3. ChatGPT应用与实践初探

    近期,长江商学院EMBA38期&甄知科技开展了题为"ChatGPT应用与实践初探"的线下沙龙活动,由上海甄知科技创始合伙人兼CTO张礼军主讲,主要给大家解密最近很火的Cha ...

  4. 支付宝spi接口设计验签和返回结果加签注意点,支付宝使用JSONObject对象

    支付宝spi接口设计验签和返回结果加签注意点,支付宝使用JSONObject对象 SPI 三方服务接入指南https://opendocs.alipay.com/isv/spiforisv 服务端实现 ...

  5. ElasticSearch服务Java内存异常分析和排查解决

    ElasticSearch服务Java内存异常分析和排查解决 1.ElasticSearch业务微服务日志排查java.lang.IllegalStateException: Request cann ...

  6. xxlJob端口号及故障转移设置,解决负载均衡调度任务执行

    xxlJob端口号及故障转移设置,解决负载均衡调度任务执行 my.xxljob.executorPort = 1162 my.xxljob.executorAppName = myService-jo ...

  7. apollo配置中心从数据库中查询所有的配置及项目

    apollo配置中心从数据库中查询所有的配置及项目 需求背景:如果需要从Apollo查询某个配置项做批量的更新替换,如果一个一个找不合适且容易遗漏,需要从底层数据库表中模糊查询来实现. 1.查看apo ...

  8. 《最新出炉》系列入门篇-Python+Playwright自动化测试-51- 字符串操作 - 上篇

    1.简介 在日常的自动化测试工作中进行断言的时候,我们可能经常遇到的场景.从一个字符串中找出一组数字或者其中的某些关键字,而不是将这一串字符串作为结果进行断言.这个时候就需要我们对字符串进行操作,宏哥 ...

  9. 在Ubuntu系统安装Anaconda及Python

      本文介绍在Linux Ubuntu操作系统的电脑中,安装Anaconda环境与Python语言的方法.   在之前的文章Anaconda与Python环境在Windows中的部署中,我们介绍了在W ...

  10. mysql在把子查询结果作为删除表中数据的条件,mysql不允许在子查询的同时删除原表数据

    在上一文中发布了多表删除指定记录,发现达不到我想要的效果,找了很多资料,发现以下方法. 数据库不能边查询边删除, 尝试以下操作 delete from push_msg_overview where ...