implement mat2gray in Opencv with Python
<p>I have the same problem with him: <a href="http://http://stackoverflow.com/questions/27483013/scaling-a-matrix-in-opencv" rel="nofollow">Scaling a matrix in OpenCV</a></p>

<p>I got the same problem with him, I have a colored picture, I used matlab to read the picture: <code>Input = imread('input1.jpg');</code>, and the format of the picture is 612x612x3 uint8,  I print the 5x5x1 pixel in the picture as below:<code>Input(1:5,1:5,1)</code></p>

<pre><code> 201   201   201   201   201
 201   201   201   201   201
 202   202   202   202   202
 203   203   203   203   203
 204   204   204   204   204
</code></pre>

<p>by using the mat2gray function: <code>rgb_out = mat2gray(Input);</code>, these pixels can be transformed to this, they all in the range between 0 and 1: <code>rgb_out(1:5,1:5,1)</code></p>

<pre><code>0.9684    0.9455    0.9266    0.9099    0.9047
0.9657    0.9542    0.9432    0.9354    0.9299
0.9642    0.9571    0.9502    0.9495    0.9456
0.9621    0.9609    0.9562    0.9532    0.9516
0.9673    0.9633    0.9597    0.9580    0.9575
</code></pre>

<p>so the question is how can I implement this in Opencv with Python, I tried the code as below:</p>

<pre><code>print(Input)
rgb_out = np.zeros(Input.shape, np.uint8)
cv2.normalize(Input,rgb_out,1,0,cv2.NORM_MINMAX)
print(rgb_out)
</code></pre>

<p>but the first print is :</p>

<pre><code>[[[205 207 201]
  [205 207 201]
  [205 207 201]
  ..., 
  [232 254 242]
  [232 254 242]
  [231 253 241]]...
</code></pre>

<p>and the elements in the rgb_out is no more than 1 or 0. please help, thanks.</p>

<p>Your input matrix is an integer datatype and your output  matrix is defined to be <code>np.uint8</code> (an integer type). By default, <code>cv2.normalize</code> is going to return a result that is the same datatype as the inputs. You'll want to use floating point datatypes if you want output values between <code>0.0</code> and <code>1.0</code>. </p>

<p>One option would be to convert your input and outputs to <code>np.double</code> prior to calling <code>cv2.normalize</code></p>

<pre><code>A = np.double(A)
out = np.zeros(A.shape, np.double)
normalized = cv2.normalize(A, out, 1.0, 0.0, cv2.NORM_MINMAX)
</code></pre>

<p>Alternately, you can specify a floating point datatype to <code>cv2.normalize</code> via the <code>dtype</code> kwarg to force a specific output datatype. </p>

<pre><code>A = np.array([1, 2, 3])
out = np.zeros(A.shape, np.double)
normalized = cv2.normalize(A, out, 1.0, 0.0, cv2.NORM_MINMAX, dtype=cv2.CV_64F)
</code></pre>

python matlab opencv