【问题标题】:OpenCV (Python) video subplotsOpenCV (Python) 视频子图
【发布时间】:2026-01-31 20:45:01
【问题描述】:

我试图在与子图相同的图中显示两个 OpenCV 视频源,但找不到如何做到这一点。当我尝试使用plt.imshow(...), plt.show() 时,窗口甚至不会出现。当我尝试使用cv2.imshow(...) 时,它显示了两个独立的数字。我真正想要的是子图:(。有什么帮助吗?

这是我目前的代码:

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()

更新:理想情况下,输出应如下所示:

【问题讨论】:

    标签: python opencv matplotlib subplot


    【解决方案1】:

    您可以简单地使用cv2.hconcat()方法将2张图片横向拼接,然后使用imshow显示,但请注意图片必须是相同的sizetype 为他们申请hconcat

    您也可以使用vconcat 垂直连接图像。

    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()
    

    【讨论】:

    • 我刚试过,效果很好。问题是我不能放置matplotlib 风格的标题:(在这方面有什么建议吗?
    • 如果你能显示预期的输出,那么我可以帮助你
    • @RafazZ 你知道如何在 opencv 中添加图片标题吗?
    • 不——没找到方法 :(
    • 您可以尝试vconcat 在这两个图像中的每一个上添加标题,然后再执行hconcat @Roxanne @RafazZ