Jame
Jame

Reputation: 3854

How to convert pixel value to another value based on given csv file?

I have a 2D image label (value from 0 to 20). I want to change the pixel values in the image to another value based on the table in the csv file

Original value     New value

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

We can do it as by a simple way likes

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

For above way, I need at least 20 lines for converting, and careful look at the table in CSV file to fill out the value in the conditions. Do we have a better way? I am using python 3.6

updated: The csv file likes

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

the first row is just the name, we do not care it

Upvotes: 1

Views: 183

Answers (1)

Dux
Dux

Reputation: 1246

Using numpy arrays:

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 now contains 6 rows with the old number as first and the new number as second element. By looping over the number of rows we can change the pixel values:

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]])

test.txt:

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

Edit:

If your data is in a .csv file like in your updated question, simply tweak the loadtxt call:

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

This way we ignore the first column (numpy doesn't work with arrays of mixed types (float and string)) and we change the delimiter from whitespace to comma. NOTE: The file extension is not important here, it can be either .txt or .csv or anything else. Only the file content is important.

Upvotes: 1

Related Questions