2

I want to convert a numpy matrix with positive and negative values of type np.float to a grayscale image with pixels from [0,255]. I want to do that as fast as possible.

Right now I am doing the following:

import numpy as np
n = 1000
I = np.random.randn(n,n)
I_min = np.min(I)
I = I + np.abs(I_min)
I_max = np.max(I)
I = 255 * (I / I_max)
I = I.astype(np.uint8)

I hope that is correct!? Is there a faster way to do that? What can be improved?

Gilfoyle
  • 3,282
  • 3
  • 47
  • 83
  • 1
    Your code does not work when I_min is positive. I think `I = I + np.abs(I_min)` should be `I = I - I_min`. – klim Oct 26 '18 at 00:41
  • You want to multiply by 255.999 instead of 255, otherwise 255 will be underrepresented in the output. – Mark Ransom Oct 26 '18 at 00:49

1 Answers1

4

You can do that with the smaller number of lines.

min_ = np.min(I)
max_ = np.max(I)
GI = (255 * (I-min_) / (max_-min_)).astype(np.uint8)
klim
  • 1,179
  • 8
  • 11
  • Nice! I did exactly the same but found it takes 485 microsec to do `np.min()` followed by `np.max()` as you did, but only 380 microsec to the `np.min()` on a separate thread in parallel while the main thread does `np.max()`. I didn't try splitting the final line of maths across multiple threads... yet! – Mark Setchell Oct 26 '18 at 01:11
  • @MarkSetchell is there no way of knowing ahead of time what your min and max are so you can skip that step entirely? – Mark Ransom Oct 26 '18 at 02:37
  • Does it make more sense to multiply by 255.9999 instead of 255 as suggested by @MarkRansom? – Gilfoyle Oct 26 '18 at 07:50
  • 1
    @Samuel It is up to you. This will help. https://stackoverflow.com/questions/1914115/converting-color-value-from-float-0-1-to-byte-0-255 – klim Oct 26 '18 at 08:13