Advertisement
dan-masek

https://stackoverflow.com/questions/74743995/replace-cells-in-ndarray-with-specific-value-one-after-

Dec 9th, 2022
1,243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. import numpy as np
  2.  
  3. # Example foreground
  4. fg = np.ones((160, 160, 4), dtype=np.uint8)
  5. fg[10,10] = [0,0,0,0]
  6. fg[20,20] = [0,0,0,1]
  7. fg[30,30] = [0,0,1,0]
  8. fg[40,40] = [0,1,0,0]
  9. fg[50,50] = [1,0,0,0]
  10. fg[60,10] = [0,0,0,0]
  11. fg[10,70] = [0,0,0,0]
  12.  
  13. # Example background
  14. bg = np.random.randint(0, 255, (1440, 1920, 4))
  15.  
  16. # Find coordinates of all pixels with (0,0,0,0)
  17. fg_zero_pos = np.where((fg == (0,0,0,0)).all(axis=2))
  18.  
  19. # Count them
  20. fg_zero_count = len(fg_zero_pos[0])
  21.  
  22. # Create random replacement coordinates for each element of
  23. r = np.random.randint(0, bg.shape[0]-1, fg_zero_count)
  24. c = np.random.randint(0, bg.shape[1]-1, fg_zero_count)
  25. bg_rand_pos = (r,c)
  26.  
  27. # Perform replacement
  28. fg[fg_zero_pos] = bg[bg_rand_pos]
  29.  
  30. print(fg[fg_zero_pos])
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement