implement mat2gray in Opencv with 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');, and the format of the picture is 612x612x3 uint8, I print the 5x5x1 pixel in the picture as below: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);, these pixels can be transformed to this, they all in the range between 0 and 1: 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.

Asked By: Chris

||

Answers:

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)
Answered By: Suever

Referenced from @Suever answer, here my working one with the identical variable to Matlab’s mat2gray.

# python function replica of matlab's mat2gray
def matlab_mat2grey(A = false, alpha = min(A.flatten()), beta = max(A.flatten())):
  I = A
  cv2.normalize(A, I, alpha , beta ,cv2.NORM_MINMAX)
  I = np.uint8(I)
  return I
Answered By: user3814219
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.