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

前端 未结 6 1918
不思量自难忘°
不思量自难忘° 2020-12-13 02:09

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

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 02:21

    The images c, d, e , and f in the following show colorspace conversion they also happen to be numpy arrays :

    import numpy, cv2
    def show_pic(p):
            ''' use esc to see the results'''
            print(type(p))
            cv2.imshow('Color image', p)
            while True:
                k = cv2.waitKey(0) & 0xFF
                if k == 27: break 
            return
            cv2.destroyAllWindows()
    
    b = numpy.zeros([200,200,3])
    
    b[:,:,0] = numpy.ones([200,200])*255
    b[:,:,1] = numpy.ones([200,200])*255
    b[:,:,2] = numpy.ones([200,200])*0
    cv2.imwrite('color_img.jpg', b)
    
    
    c = cv2.imread('color_img.jpg', 1)
    c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)
    
    d = cv2.imread('color_img.jpg', 1)
    d = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)
    
    e = cv2.imread('color_img.jpg', -1)
    e = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)
    
    f = cv2.imread('color_img.jpg', -1)
    f = cv2.cvtColor(c, cv2.COLOR_RGB2BGR)
    
    
    pictures = [d, c, f, e]
    
    for p in pictures:
            show_pic(p)
    # show the matrix
    print(c)
    print(c.shape)
    

    See here for more info: http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

    OR you could:

    img = numpy.zeros([200,200,3])
    
    img[:,:,0] = numpy.ones([200,200])*255
    img[:,:,1] = numpy.ones([200,200])*255
    img[:,:,2] = numpy.ones([200,200])*0
    
    r,g,b = cv2.split(img)
    img_bgr = cv2.merge([b,g,r])
    

提交回复
热议问题