python - 如何根据给定的csv文件将像素值转换为另一个值?

标签 python python-3.x

我有一个 2D 图像标签(值从 0 到 20)。我想根据 csv 文件中的表格将图像中的像素值更改为另一个值

Original value     New value

0                      0
1                      23
2                      2
3                      11
4                      11
5                      15
...

我们可以通过像这样的简单方式来做到这一点

label[label==0]=0
label[label==1]=23
label[label==2]=2
label[label==3|label==4]=11
label[label==5]=15

对于上述方式,我需要至少20行进行转换,并仔细查看CSV文件中的表格以填写条件中的值。我们有更好的办法吗?我正在使用 python 3.6

更新: csv 文件喜欢

label1, 0, 0
label2, 1, 23
label3, 2, 2
label4, 3, 11
label5, 4, 11
label6, 5, 15

第一行只是名称,我们不关心它

最佳答案

使用numpy数组:

import numpy as np

Data = np.arange(25).reshape((5,5))

#Data
#array([[ 0,  1,  2,  3,  4],
#       [ 5,  6,  7,  8,  9],
#       [10, 11, 12, 13, 14],
#       [15, 16, 17, 18, 19],
#       [20, 21, 22, 23, 24]])

switch = np.loadtxt('./test.txt', comment='#')

switch 现在包含 6 行,其中旧数字作为第一个元素,新数字作为第二个元素。通过循环行数,我们可以更改像素值:

for i in range(switch.shape[0]):
    Data[Data == switch[i, 0]] = switch[i, 1]

#Data
#array([[ 0, 23,  2, 11, 11],
#       [15,  6,  7,  8,  9],
#       [10, 11, 12, 13, 14],
#       [15, 16, 17, 18, 19],
#       [20, 21, 22, 23, 24]])

测试.txt:

#old                  new
0                      0
1                      23
2                      2
3                      11
4                      11
5                      15

编辑:

如果您的数据位于 .csv 文件中(如更新的问题所示),只需调整 loadtxt 调用即可:

switch = np.loadtxt('./text.txt', usecols=(1,2), delimiter=',')

这样我们就忽略了第一列(numpy 不适用于混合类型( float 和字符串)的数组),并将分隔符从空格更改为逗号。 注意:文件扩展名在这里并不重要,它可以是 .txt 或 .csv 或其他任何名称。只有文件内容很重要。

关于python - 如何根据给定的csv文件将像素值转换为另一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673068/

相关文章:

Python线程运行()阻塞

python-3.x - DynamoDB 扫描未返回所需的输出

python - 添加多线程或异步到网络抓取

python - 拆分后我的 readline() 的空字符串是什么

python - 扭曲的 websockets 导入错误

python - 如何在Python中将字典转换为数据框

python - 两个或多个数据框的完全外部连接

python-3.x - 使用 Keras 的生成器 model.fit_generator

python - 重写时如何模拟基类的方法?

python - 具有大对象的 Memcached(NetworkX 图)