Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV (Python) video subplots

I am trying to show two OpenCV video feeds in the same figure as subplots, but couldn't find how to do it. When I try using plt.imshow(...), plt.show(), the window won't even appear. When I try using cv2.imshow(...), it shows two independent figures. What I actually want are subplots :(. Any help?

Here is the code that I have so far:

import numpy as np
import cv2
import matplotlib.pyplot as plt

cap = cv2.VideoCapture(0)
ret, frame = cap.read()

while(True):
    ret, frame = cap.read()
    channels = cv2.split(frame)
    frame_merge = cv2.merge(channels)

    #~ subplot(211), plt.imshow(frame)
    #~ subplot(212), plt.imshow(frame_merged)
    cv2.imshow('frame',frame)
    cv2.imshow('frame merged', frame_merge)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

UPDATE: Ideally the output should look something like that:

Subplots for OpenCV videos

like image 402
RafazZ Avatar asked Sep 13 '25 09:09

RafazZ


1 Answers

You may simply use the cv2.hconcat() method to horizontally join 2 images and then display using imshow, But keep in mind that the images must be of same size and type for applying hconcat on them.

You may also use vconcat to join the images vertically.

import numpy as np
import cv2
import matplotlib.pyplot as plt

cap = cv2.VideoCapture(0)
ret, frame = cap.read()

bg = [[[0] * len(frame[0]) for _ in xrange(len(frame))] for _ in xrange(3)]

while(True):
    ret, frame = cap.read()
    # Resizing down the image to fit in the screen.
    frame = cv2.resize(frame, None, fx = 0.5, fy = 0.5, interpolation = cv2.INTER_CUBIC)

    # creating another frame.
    channels = cv2.split(frame)
    frame_merge = cv2.merge(channels)

    # horizintally concatenating the two frames.
    final_frame = cv2.hconcat((frame, frame_merge))

    # Show the concatenated frame using imshow.
    cv2.imshow('frame',final_frame)

    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()
like image 193
ZdaR Avatar answered Sep 15 '25 23:09

ZdaR