【问题标题】:OpenCV draw contours (Jupyter Notebook)OpenCV 绘制轮廓(Jupyter Notebook)
【发布时间】:2021-01-17 00:09:38
【问题描述】:

我从 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 内核会死掉。我应该改变什么?

【问题讨论】:

  • 您是否通过逐个单元格分隔来调试代码?代码正在运行。如果您愿意,我可以解释并分享我的代码作为答案。
  • 可能与waitKey(0)有关。在 Jupyter 中不起作用。
  • @GilPinsky 在 Jupyter 中应该使用什么? (我试过完全不用waitKey,还是不行)
  • @obart 你说的没用是什么意思?没显示?您可以尝试使用 matplotlib 显示结果: import matplotlib.pyplot as plt ,并使用 plt.imshow(im)。
  • @GilPinsky 是的,没有显示。我尝试使用 plt.imshow(im),但是显示的图像是原始图像,我想显示轮廓。谢谢!

标签: python opencv jupyter-notebook opencv-drawcontour


【解决方案1】:

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

【讨论】:

  • 我拥有的图像(问题中的“im”)是二进制图像。我要显示的结果是该二值图像的轮廓。我应该对您评论中的代码进行哪些修改以使其适用于二进制输入图像? [结果应该只是轮廓]谢谢!
  • 查看我的更新答案。您需要将im 制作为3 通道图像,因此请使用np.expand_dimsrepeat,如图所示。如果您只想要轮廓,请在 for 循环之前将 im 初始化为零 numpy.ndarray,形状为 H X W X 3。
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 2014-05-25
  • 2019-01-25
  • 2019-02-12
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多