Cannot transfer Pixel to image in correct in right shape from cv code to cv2 code
Question: Recently I trying to do some image processing for my work. Unfortunately that
I keep trying to apply my old C++ code with cv support to python code with cv2
support. It cannot work very well... Can anyone help me?

Original C++ Code:

    
    
    #define IMAGE_WIDE  40
    #define IMAGE_LENGTH    30
    #define CHANNELS    3
    
    DNN_image_out = cvCreateImage(cvSize(IMAGE_WIDE, IMAGE_LENGTH), IPL_DEPTH_8U, 3);
    for(int k = 0; k < IMAGE_LENGTH; k++){  //縦
            for(int l = 0; l < IMAGE_WIDE; l++){    //横
                DNN_image_out[i]->imageData[(k * IMAGE_WIDE + l)*3 +0] = DNN_image_tmp[(k * IMAGE_WIDE + l)*3 + 0 ];
                DNN_image_out[i]->imageData[(k * IMAGE_WIDE + l)*3 +1] = DNN_image_tmp[(k * IMAGE_WIDE + l)*3 + 1 ];
                DNN_image_out[i]->imageData[(k * IMAGE_WIDE + l)*3 +2] = DNN_image_tmp[(k * IMAGE_WIDE + l)*3 + 2 ];
            }
        }
    

* * *

My Python CV2 code:

    
    
    import numpy as np
    import cv2
    
    def split_channel3(array,width,height):
        R=[]
        G=[]
        B=[]
        for k in range(height):
            for l in range(width):
                R.append(array[(k * width + l)*3 +0])
                G.append(array[(k * width + l)*3 +1])
                B.append(array[(k * width + l)*3 +2])
        R = np.asarray(R)
        G = np.asarray(G)
        B = np.asarray(B)
        return [R,G,B]
    
    
    [R,G,B] = split_channel3(img,40,30)
    R = R.reshape(40,30,1)
    G = G.reshape(40,30,1)
    B = B.reshape(40,30,1)
    Color_img = np.dstack((R,G))
    Color_img = np.dstack((Color_img,B))
    cv2.imshow('image',Color_img)
    cv2.waitKey(0)
    

Is my logic wrong? Or what should I change in python code?


Answer: You can simply use `cv2.split`, without the need of your custom function nor
`reshape`:

    
    
    B,G,R = cv2.split(img)
    

and then evantually use:

    
    
    Color_img  = cv2.merge((B,G,R))
    

Remember that the channels are B,G,R by default in OpenCV, and not R,G,B.

