How to convert 1ch image to 3ch with opencv2?

I'm really puzzled by this. I have an image that used to be [BGR2GRAY] in my code and now I need to add colored circles and the like. Of course it can't be done in a 1 channel matrix and I can't turn this damn thing back into 3.

numpy.dstack () crashes everything

GRAY2BGR does not exist in opencv2

cv.merge (src1, src2, src3, dst) has been turned into cv2.merge (mv), where mv = "matrix vector", whatever that means.

Any ideas?

Opencv2.4.3 refmanual

+9


source to share


4 answers


Here's a way to do it in Python:

img = cv2.imread("D:\\img.jpg")
gray = cv2.cvtColor(img, cv.CV_BGR2GRAY)

img2 = np.zeros_like(img)
img2[:,:,0] = gray
img2[:,:,1] = gray
img2[:,:,2] = gray

cv2.circle(img2, (10,10), 5, (255,255,0))
cv2.imshow("colour again", img2)
cv2.waitKey()

      



Here is the complete code for OpenCV3:

import cv2
import numpy as np
img = cv2.imread('10524.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2 = np.zeros_like(img)
img2[:,:,0] = gray
img2[:,:,1] = gray
img2[:,:,2] = gray
cv2.imwrite('10524.jpg', img2)

      

+10


source


This is the Python equivalent: imgray is an empty array containing a 1-channel image.



img2 = cv2.merge((imgray,imgray,imgray))

      

+3


source


I can't tell you about python, but I can tell you the C ++ interface ...

gray_image //you have it already
Mat im_coloured = Mat::zeros(gray_image.rows,gray_image.cols,CV_8UC3);

vector<Mat> planes;

for(int i=0;i<3;i++)
    planes.push_back(gray_image);

merge(planes,im_coloured);

      

+1


source


Below I am assuming you do not have a 3-channel image in the correct shape, so the zeros_like function (used in the answer above) will not be helpful.

img2 = np.zeros( ( np.array(img).shape[0], np.array(img).shape[1], 3 ) )
img2[:,:,0] = img # same value in each channel
img2[:,:,1] = img
img2[:,:,2] = img

      

if img is a numpy array it can be shortened from np.array(img).shape

toimg.shape

0


source







All Articles