0
video = 'test.avi'
cap = cv2.VideoCapture(video)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fps = round(cap.get(cv2.CAP_PROP_FPS))
size = (width, height)
fourcc = cv2.VideoWriter_fourcc(*'XVID')

# noinspection PyArgumentList
out = cv2.VideoWriter("output.avi", fourcc, fps, size)

while cap.isOpened():
    ret, frame = cap.read()
    if frame is None:
        print('\nEnd of Video')
        break
    frame = plt.imread(frame)
##########################################################
    im = np.array(Image.open(frame), dtype=np.uint8)
    fig, ax = plt.subplots(1)
    ax.imshow(im)
    bbox = patches.Rectangle((50, 100), 100, 130, linewidth=2, edgecolor='r', facecolor='none')
    ax.add_patch(bbox)
    font = {'family': 'sans-serif',
            # 'color': 'darkred',
            'weight': 'book',
            'size': 10,
            }
    plt.text(50, 100, s='labels', color='white', fontdict=font, verticalalignment='top',
             bbox={'color': 'red', 'pad': 0})
    # plt.show()
    fig.savefig(frame)
##########################################################
    out.write(frame)
cap.release()
out.release()

I want to draw rectangle boxes in each frame in video and save them. Above my code, frame = plt.imread(frame) makes TypeError: Object does not appear to be a 8-bit string path or a Python file-like object error. How can I use matplot with cv2? (This code is written in python)

DavidG
  • 24,279
  • 14
  • 89
  • 82
Nazzzz
  • 55
  • 2
  • 7
  • Does it **have** to be done with `matplotlib`? The `cv2.drawRectangle()` handles this quite well, as shown on [this answer](https://stackoverflow.com/a/23720964/7731997). If not, there might be some ways to do it with mpl, involving temporarily saving each frame, reopening it with `plt.imread()`, drawing the rectangles, saving again, and reopening again with `cv2`. – Gabriel Jablonski Jul 17 '18 at 13:03
  • @DavidG Because of the text background, I tried to use matplotlib. Can I apply text background color with cv2? – Nazzzz Jul 17 '18 at 16:08

0 Answers0