14

Is it possible to have black-and-white and color image on same window by using opencv libraray? How can I have both of these images on same window?

4 Answers4

37

fraxel's answer has solved the problem with old cv interface. I would like to show it using cv2 interface, just to understand how this easy in new cv2 module. (May be it would be helpful for future visitors). Below is the code:

import cv2
import numpy as np

im = cv2.imread('kick.jpg')
img = cv2.imread('kick.jpg',0)

# Convert grayscale image to 3-channel image,so that they can be stacked together    
imgc = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
both = np.hstack((im,imgc))

cv2.imshow('imgc',both)
cv2.waitKey(0)
cv2.destroyAllWindows()

And below is the output I got:

enter image description here

Abid Rahman K
  • 51,886
  • 31
  • 146
  • 157
  • @abid-rahman-k can the same be done with videos? without turning one into greyscale? –  Mar 24 '15 at 18:46
9

Yes it is, here is an example, expaination in the comments:

enter image description here

import cv
#open color and b/w images
im = cv.LoadImageM('1_tree_small.jpg')
im2 = cv.LoadImageM('1_tree_small.jpg',cv.CV_LOAD_IMAGE_GRAYSCALE)
#set up our output and b/w in rgb space arrays:
bw = cv.CreateImage((im.width,im.height), cv.IPL_DEPTH_8U, 3)
new = cv.CreateImage((im.width*2,im.height), cv.IPL_DEPTH_8U, 3)
#create a b/w image in rgb space
cv.Merge(im2, im2, im2, None, bw)
#set up and add the color image to the left half of our output image
cv.SetImageROI(new, (0,0,im.width,im.height))
cv.Add(new, im, new)
#set up and add the b/w image to the right half of output image
cv.SetImageROI(new, (im.width,0,im.width,im.height))
cv.Add(new, bw, new)
cv.ResetImageROI(new)
cv.ShowImage('double', new)
cv.SaveImage('double.jpg', new)
cv.WaitKey(0)

Its in python, but easy to convert to whatever..

fraxel
  • 34,470
  • 11
  • 98
  • 102
2

Small improvement to the code with modern writing

concatenate

instead of

hstack

that is discontinued (stack can also be used)

import cv2
import numpy as np

im = cv2.imread('kick.jpg')
img = cv2.imread('kick.jpg',0)

# Convert grayscale image to 3-channel image,so that they can be stacked together    
imgc = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
both = np.concatenate((im,imgc), axis=1)   #1 : horz, 0 : Vert. 

cv2.imshow('imgc',both)
cv2.waitKey(0)
cv2.destroyAllWindows()
  • Has anyone profiled `cv2.hconcat()` versus `np.concatenate()`? I use the former, as I prefer to stick with opencv when possible in my code instead of numpy, but I suppose I should run the numbers. – eric May 06 '19 at 14:42
-2
import cv2
img = cv2.imread("image.jpg" , cv2.IMREAD_GRAYSCALE)
cv2.imshow("my image",img)
cv2.waitkey(0)
cv2.destroyAllWindow


#The image file should be in the application folder.
#The output file will be 'my image' name.
#The bottom line is to free up memory.