Reputation: 33
I have an image where some color channels in the pixels have a value of zero (ie 255, 146, 0). I want to be able to change any value equal to zero in the array to a different value, but I do not know how to access these values. Any help with this?
This is the image array:
[[[ 76 163 168]
[109 166 168]
[173 172 167]
...,
[ 83 182 144]
[ 78 172 134]
[ 82 150 131]]
[[ 51 151 168]
[ 99 157 171]
[173 195 159]
...,
[ 56 165 144]
[ 25 198 125]
[ 35 185 121]]
[[ 76 163 121]
[112 147 120]
[175 151 118]
...,
[ 57 162 159]
[ 36 185 132]
[ 32 194 97]]
...,
[[ 78 189 126]
[ 68 173 129]
[ 58 171 150]
...,
[ 41 188 163]
[ 34 176 126]
[ 35 176 102]]
[[131 155 161]
[101 141 161]
[ 42 151 177]
...,
[ 56 178 122]
[ 45 192 114]
[ 46 184 112]]
[[130 157 185]
[ 83 141 185]
[ 42 158 185]
...,
[ 63 187 88]
[ 45 194 102]
[ 45 184 129]]]
Upvotes: 2
Views: 1796
Reputation: 221514
Use masking
-
img[(img==zero_val).all(-1)] = new_val
, where zero_val
is the zero
color and new_val
is the new color to be assigned at those places where we have zero
colored pixels.
Sample run -
# Random image array
In [112]: img = np.random.randint(0,255,(4,5,3))
# Define sample zero valued and new valued arrays
In [113]: zero_val = [255,146,0]
...: new_val = [255,255,255]
...:
# Set two random points/pixels to be zero valued
In [114]: img[0,2] = zero_val
In [115]: img[2,3] = zero_val
# Use proposed approach
In [116]: img[(img==zero_val).all(-1)] = new_val
# Verify that new values have been assigned
In [117]: img[0,2]
Out[117]: array([255, 255, 255])
In [118]: img[2,3]
Out[118]: array([255, 255, 255])
Upvotes: 1