Search code examples
pythonpython-2.7opencvwebcamopencv3.0

How do I get a video feed to shrink to fit a window using OpenCV Beta 3.0.0 and Python 2.7.5?


I am working on a project where I need to display 3 webcam feeds side by side on a single screen. I have the feeds side by side, but the video isn't fully displaying on the windows. How do I make the video auto-fit to the window? Thanks!

Here's the code:

import cv2

window_x = 340
window_y = 340

capture1 = cv2.VideoCapture(0)
capture2 = cv2.VideoCapture(1)
capture3 = cv2.VideoCapture(3)

while True:
    cv2.namedWindow("frame1")
    cv2.namedWindow("frame2")
    cv2.namedWindow("frame3")

    cv2.moveWindow("frame1",0,0)
    cv2.moveWindow("frame2",window_x,0)
    cv2.moveWindow("frame3",window_x * 2,0)

    cv2.resizeWindow("frame1",window_x,window_y)
    cv2.resizeWindow("frame2",window_x,window_y)
    cv2.resizeWindow("frame3",window_x,window_y)

    ret, frame1 = capture1.read()
    ret, frame2 = capture2.read()
    ret, frame3 = capture3.read()

    cv2.imshow("frame1",frame1)
    cv2.imshow("frame2",frame2)
    cv2.imshow("frame3",frame3)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

capture1.release()
capture2.release()
capture3.release()

cv2.destroyAllWindows()

Solution

  • In Oencv, a way to put three images into one big window is to use ROI to copy each image into the dedicate location in the big window. Below is an example of usage:

    import cv2
    import numpy as np
    
    window_x = 340
    window_y = 340
    
    cv2.namedWindow("Big picture")
    
    capture1 = cv2.VideoCapture(0)
    capture2 = cv2.VideoCapture(1)
    capture3 = cv2.VideoCapture(3)
    
    while True:
    
        ret, frame1 = capture1.read()
        ret, frame2 = capture2.read()
        ret, frame3 = capture3.read()
    
        #Create the big Mat to put all three frames into it
        big_frame = m = np.zeros((window_y, window_x*3, 3), dtype=np.uint8)
    
        # Resize the frames to fit in the big picture
        frame1 = cv2.resize(frame1, (window_y, window_x)) 
        frame2 = cv2.resize(frame2, (window_y, window_x))
        frame3 = cv2.resize(frame3, (window_y, window_x))
        rows,cols,channels = frame1.shape
    
        #Add the first frame to the big picture
        roi = big_frame[0:cols, 0:rows]
        dst = cv2.add(roi,frame1)
        big_frame[0:cols, 0:rows] = dst
    
        #Add second frame to the big picture
        roi = big_frame[0:cols, rows:rows*2]
        dst = cv2.add(roi,frame2)
        big_frame[0:cols, rows:rows*2] = dst
    
        #Add third frame to the big picture
        roi = big_frame[0:cols, rows*2:rows*3]
        dst = cv2.add(roi,frame3)
        big_frame[0:cols, rows*2:rows*3] = dst
    
        cv2.imshow("Big picture", big_frame)
    
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    capture1.release()
    capture2.release()
    capture3.release()
    
    cv2.destroyAllWindows()