Chris - 1 year ago 284

Python Question

I have the same problem with him: Scaling a matrix in OpenCV

I got the same problem with him, I have a colored picture, I used matlab to read the picture:

`Input = imread('input1.jpg');`

`Input(1:5,1:5,1)`

`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

by using the mat2gray function:

`rgb_out = mat2gray(Input);`

`rgb_out(1:5,1:5,1)`

`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

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

`print(Input)`

rgb_out = np.zeros(Input.shape, np.uint8)

cv2.normalize(Input,rgb_out,1,0,cv2.NORM_MINMAX)

print(rgb_out)

but the first print is :

`[[[205 207 201]`

[205 207 201]

[205 207 201]

...,

[232 254 242]

[232 254 242]

[231 253 241]]...

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

Answer Source

Your input matrix is an integer datatype and your output matrix is defined to be `np.uint8`

(an integer type). By default, `cv2.normalize`

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 `0.0`

and `1.0`

.

One option would be to convert your input and outputs to `np.double`

prior to calling `cv2.normalize`

```
A = np.double(A)
out = np.zeros(A.shape, np.double)
normalized = cv2.normalize(A, out, 1.0, 0.0, cv2.NORM_MINMAX)
```

Alternately, you can specify a floating point datatype to `cv2.normalize`

via the `dtype`

kwarg to force a specific output datatype.

```
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)
```