Advertisement
dan-masek

Solution to https://stackoverflow.com/questions/69319883/convert-a-csv-file-to-image-for-opencv

Sep 24th, 2021
1,019
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3.  
  4.  
  5. print('Loading CSV...')
  6. raw = np.loadtxt('HEA_515_01.csv', delimiter=';', skiprows=1)
  7. print('Loaded %d rows.' % len(raw))
  8.  
  9. # Split the array for convenience...
  10. x = raw[:,0]
  11. y = raw[:,1]
  12. value = raw[:,2]
  13.  
  14. min_x, max_x = x.min(), x.max()
  15. min_y, max_y = y.min(), y.max()
  16. min_val, max_val = value.min(), value.max()
  17.  
  18. # Determine output image size....
  19. count_x = len(np.unique(x))
  20. count_y = len(np.unique(y))
  21.  
  22. # Calculate accurate step sizes
  23. step_x = (max_x - min_x) / (count_x - 1)
  24. step_y = (max_y - min_y) / (count_y - 1)
  25.  
  26. # Remap x and y to pixel coordinates
  27. x = np.int32(np.rint((x - min_x) / step_x))
  28. y = np.int32(np.rint((y - min_y) / step_y))
  29.  
  30. # Normalize values to range [0.0, 1.0]
  31. value = (value - min_val) / max_val
  32.  
  33. # Create destination array...
  34. result = np.full((count_y, count_x), np.nan)
  35.  
  36. # Assign the values...
  37. result[y,x] = value
  38.  
  39. assert(np.count_nonzero(np.isnan(result)) == 0)
  40.  
  41. cv2.imwrite('output.png', np.uint8(result * 255))
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement