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
272 views
in Technique[技术] by (71.8m points)

python - Opencv or Numpy-- replace a list of pixels in an image, efficiently

Hi OpenCV or Numpy Gurus,

I've been searching to an answer to this, but I'm surprised to not find it here or elsewhere...

I have a black image, and I want to replace a list of pixels (quite a large list) with a certain value. In the future, the "certain value" will be a list of values, but for the moment, let's keep it simple.

Simplifying even further, I just use a 2-d array of single numbers below, instead of RGB values... So, this fairly inefficient approach works for this sort of thing:

a = np.zeros((5, 5,1))

for i in np.asarray( ([2,3],[3,4]) ):
       a[i[0], i[1]] = 20

I was hoping there was a way to use np.put on a two dimensional array, where I don't rely on a python loop.

Now I had the suggestion that I could use

a[ ([2,3],[3,4]) = 20

However I notice when I use this approach in my real OpenCV problem it does not work. This very inefficient approach does:

coords_list = ([3,5],[55,60],[25,90])
black_image =np.zeros((480,640,3))
for i in coords_list:
    black_image[i[1],i[0]] = [255,255,255]

I expect this is a simple question to many out there.

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In fact, you can directly use your tuple of coordinates to index your matrix: a simple a[([2, 3], [3, 4])] = 20 gives the exact same result as your for loop here.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...