Search code examples
pythonopencvrgbnumpy-ndarrayhsv

Error: only size-1 arrays can be converted to Python scalars


i'm working on numpt matrix, i can create an HSV image and after convert it in RGB image. i create a matrix HSV with: matrix_=np.zeros([3, H-kernel+1, W-kernel+1], dtype=np.float32)

after i have filled it with magnitudes, 255, theta of angle, to each value: matrix_[:, row, column]=np.array([th, 255, mag]) finally i convert it with: cv2.cvtColor(matrix_, matrix_, cv2.COLOR_HSV2RGB)

but it throws: "TypeError: only size-1 arrays can be converted to Python scalars" in line of cv2.cvtColor. why? where i wrong?


Solution

  • You are mixing the order of the arguments.

    See documentation of cvtColor:

    Python: cv2.cvtColor(src, code[, dst[, dstCn]]) → dst

    As you can see the destination matrix is the third argument.
    The code is the second argument.
    The code should be scalar, but you are passing matrix_ as second argument, so you are getting the error:
    "TypeError: only size-1 arrays can be converted to Python scalars".

    For avoiding the error, you may use:

    cv2.cvtColor(matrix_, cv2.COLOR_HSV2RGB, matrix_)
    

    You better use the return value (the syntax is more clear):

    matrix_ = cv2.cvtColor(matrix_, cv2.COLOR_HSV2RGB)
    

    Now there is another exception: "Invalid number of channels in input image".

    You have set the matrix shape wrong:

    Instead of matrix_=np.zeros([3, H-kernel+1, W-kernel+1], dtype=np.float32), it should be:

    matrix_=np.zeros([H-kernel+1, W-kernel+1, 3], dtype=np.float32)
    

    The syntax matrix_[:, row, column]=np.array([th, 255, mag]) looks weird.
    You didn't post the values of row, column, th and mag.
    I can't say if it is correct or not.
    I must assume it is out of the scope of your question...