1

I used Opencv to open my camera, then I want to show the image bu matplotlib. However, the frames freezes. Can I use matplotlib in real-time? Thank you!

cap = cv2.VideoCapture(0)    
while (True):
    ret, frame = cap.read()
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    plt.subplot(1,2,1), plt.imshow(frame, interpolation='nearest')  
    plt.show()
SUN JIAWEI
  • 117
  • 1
  • 1
  • 8

1 Answers1

2

You can use plt.ion() to enable interactive plotting.

import matplotlib.pyplot as plt
import cv2

cap = cv2.VideoCapture(0)    
plt.ion()

while (True):
    ret, frame = cap.read()
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    plt.subplot(1,2,1), plt.imshow(frame, interpolation='nearest')  
    plt.pause(0.001)
    plt.show()

In this solution you replot everything and even create a new subplot for each frame to be shown. This is highly inefficient and hence slow. Check out this answer Speed up live plotting of a footage (cv2).

I.Newton
  • 1,753
  • 1
  • 10
  • 14
  • It works! Thank you! And plt.pause(0.001), how can I change the 0.001 to make the real time faster? – SUN JIAWEI Nov 08 '17 at 06:48
  • It'll be slower because of matplotlib plt. I dont think reducing the delay will improve it much. – I.Newton Nov 08 '17 at 07:59
  • In this solution you replot everything and even create a new subplot for each frame to be shown. This is highly inefficient. See e.g. [this question](https://stackoverflow.com/questions/45586983/speed-up-live-plotting-of-a-footage-cv2) on how to prevent this. I marked as duplicate of it. – ImportanceOfBeingErnest Nov 08 '17 at 09:31
  • @ImportanceOfBeingErnest Thanks for letting me know. I edited my answer. – I.Newton Nov 08 '17 at 10:51