convert matplotlib figure to cv2 image

Solutions on MaxInterview for convert matplotlib figure to cv2 image by the best coders in the world

showing results for - "convert matplotlib figure to cv2 image"
Shea
11 Jan 2021
1import matplotlib
2matplotlib.use('TkAgg')
3
4import numpy as np
5import cv2
6import matplotlib.pyplot as plt
7
8fig = plt.figure()
9cap = cv2.VideoCapture(0)
10
11
12x1 = np.linspace(0.0, 5.0)
13x2 = np.linspace(0.0, 2.0)
14
15y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
16y2 = np.cos(2 * np.pi * x2)
17
18
19line1, = plt.plot(x1, y1, 'ko-')        # so that we can update data later
20
21for i in range(1000):
22    # update data
23    line1.set_ydata(np.cos(2 * np.pi * (x1+i*3.14/2) ) * np.exp(-x1) )
24
25    # redraw the canvas
26    fig.canvas.draw()
27
28    # convert canvas to image
29    img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8,
30            sep='')
31    img  = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
32
33    # img is rgb, convert to opencv's default bgr
34    img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
35
36
37    # display image with opencv or any operation you like
38    cv2.imshow("plot",img)
39
40    # display camera feed
41    ret,frame = cap.read()
42    cv2.imshow("cam",frame)
43
44    k = cv2.waitKey(33) & 0xFF
45    if k == 27:
46        break