Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

python - OpenCV: setting all pixels of specific BGR value to another BGR value

I am using OpenCV with Python. I have an image, and what I want to do is set all pixels of BGR value [0, 0, 255] to [0, 255, 255].

I asked a previous question on how to posterize an image, and from the answer I learned about indexing with an Array of indices, for ex: image[image > 128] = 255

I understand how this works, since image > 128 will return an array of multi-dimensional array of indices that satisfy the condition, and then I apply this array to the image and set those to 255. However, I'm getting confused with how to extend this to doing a value for an array.

I tried doing the following:

      red = np.array([0, 0, 255])
      redIndex = np.where(np.equal(image, red))
      image[redIndex] = np.array([0, 255, 255])

but it doesn't work, with the error:

ValueError: array is not broadcastable to correct shape

Is there an efficient way to handle this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider an image like array as below :

>>> red
array([[[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255]],

       [[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255],
        [  0,   0, 255]]])

Its all elements are [0,0,255]. Its shape is 2x5x3. Just think there are other values also in it. (I can't create all those).

Now you find where [0,0,255] are present and change them to [0,255,255]. You can do it as follows :

>>> red[np.where((red == [0,0,255]).all(axis = 2))] = [0,255,255]

Now check the red.

>>> red
array([[[  0, 255, 255],
        [  0, 255, 255],
        [  0, 255, 255],
        [  0, 255, 255],
        [  0, 255, 255]],

       [[  0, 255, 255],
        [  0, 255, 255],
        [  0, 255, 255],
        [  0, 255, 255],
        [  0, 255, 255]]])

Hope this is what you want.

Test Results:

Check out the code from this link : https://stackoverflow.com/a/11072667/1134940

I want to change all red pixels to yellow as asked in question.

So i added this below piece of code at the end :

im2[np.where((im2 == [0,0,255]).all(axis = 2))] = [0,255,255]

Below is the result I got :

enter image description here

What if i want to change green ground to yellow ground :

im2[np.where((im2 == [0,255,0]).all(axis = 2))] = [0,255,255]

Result :

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...