简体   繁体   中英

OpenCV draw contours (Jupyter Notebook)

I run the following code from Jupyter Notebook:

import cv2 as cv
contours, hierarchy = cv.findContours(im, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cnt = contours[4]
cv.drawContours(im, contours, 2, (0, 230, 255), 6)
# Show the image with contours
cv.imshow('Contours', im)
cv.waitKey(0)

(im is a binary image) After running this, the Jupyter Kernel dies. What should I change?

So here's a workaround. TL;DR: You need to use im = cv.drawContours(im, contours, 2, (0, 230, 255), 6) to save the drawn contours and im = np.expand_dims(im,axis=2).repeat(3,axis=2) in order to be able to draw colored contours. The following code draws all contours on im and shows it using matplotlib :

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#im an H X W array.
contours, hierarchy = cv.findContours(im, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
im = np.expand_dims(im, axis=2).repeat(3, axis=2) 
for k, _ in enumerate(contours):
    im = cv.drawContours(im, contours, k, (0, 230, 255), 6)
plt.imshow(im)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM