OpenCV绘制轮廓(Jupyter Notebook)

OpenCV draw contours (Jupyter Notebook)

我 运行 来自 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是二值图像) 在 运行 之后,Jupyter 内核就死了。我应该改变什么?

所以这里有一个解决方法。 TL;DR:您需要使用 im = cv.drawContours(im, contours, 2, (0, 230, 255), 6) 来保存绘制的轮廓和 im = np.expand_dims(im,axis=2).repeat(3,axis=2) 以便能够绘制彩色轮廓。 以下代码在 im 上绘制 all 等高线并使用 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)