[Solved] Change color in RGB images


I have to agree with Majid Shirazi regarding the proposed solution by Quang Hong. Let’s have a look at:

idx = np.where(img == (0.4, 0.4, 0.4))

Then, idx is a 3-tuple containing each a ndarray for all x-coordinates, y-coordinates, and “channel”-coordinates. From NumPy’s indexing, I can’t see a possibility to properly access/manipulate the values in img in the desired way using the proposed command. I can rather reproduce the exact error stated in the comment.

To get a proper integer array indexing, the x– and y-coordinates need to be extracted. The following code will show that. Alternatively, boolean array indexing might also be used. I added that as an add-on:

import cv2
import numpy as np

# Some artificial image
img = np.swapaxes(np.tile(np.linspace(0, 1, 201), 603).reshape((201, 3, 201)), 1, 2)
cv2.imshow('before', img)

# Proposed solution
img1 = img.copy()
idx = np.where(img1 == (0.4, 0.4, 0.4))
try:
    img1[idx] = (0.54, 0.27, 0.27)
except ValueError as e:
    print(e)

# Corrected solution for proper integer array indexing: Extract x and y coordinates
img1[idx[0], idx[1]] = (0.54, 0.27, 0.27)
cv2.imshow('after: corrected solution', img1)

# Alternative solution using boolean array indexing
img2 = img.copy()
img2[np.all(img2 == (0.4, 0.4, 0.4), axis=2), :] = (0.54, 0.27, 0.27)
cv2.imshow('after: alternative solution', img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

Hope that helps and clarifies!

solved Change color in RGB images