[Python] How to convert a python numpy array to an RGB image with Opencv 2.4?

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have searched for similar questions, but haven't found anything helpful as most solutions use older versions of OpenCV.

    I have a 3D numpy array, and I would like to display and/or save it as a BGR image using OpenCV (cv2).

    As a short example, suppose I had:

    import numpy, cv2
    b = numpy.zeros([5,5,3])

    b[:,:,0] = numpy.ones([5,5])*64
    b[:,:,1] = numpy.ones([5,5])*128
    b[:,:,2] = numpy.ones([5,5])*192


    What I would like to do is save and display b as a color image similar to:

    cv2.imwrite('color_img.jpg', b)
    cv2.imshow('Color image', b)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


    This doesn't work, presumably because the data type of b isn't correct, but after substantial searching, I can't figure out how to change it to the correct one. If you can offer any pointers, it would be greatly appreciated!

    Continue reading...

Compartilhe esta Página