0

I'm trying to read the contours from opencv and transfer it to matplotlib for display. Here is my code.

What should I do?

img = cv2.imread('sample.jpeg')
_, bin_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 180, 255,
                             cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(bin_img, mode, method)
plt.contour(contours)

It throws an error:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (111,) + inhomogeneous part.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Terminus
  • 9
  • 1
  • `contours` is not an image (or numpy array), you can't "plot" it. It is a `list`, you need to use opencv's `drawContours` function to draw the parsed contours into an image/numpy array. Check: https://docs.opencv.org/4.8.0/d4/d73/tutorial_py_contours_begin.html. Be aware tha you sitll need to create a window to show the image. – stateMachine Jul 06 '23 at 09:02
  • @stateMachine I use `np.array(contours)` instead. But it throws "ValueError: setting an array element with a sequence.". It seems like dimensional error? – Terminus Jul 06 '23 at 09:19
  • matplotlib surely is capable of plotting a list of points as a polygon. this just requires a bit of research. no, you can't just pass a list of contours (a list of np arrays) to matplotlib. – Christoph Rackwitz Jul 06 '23 at 19:48
  • Does this answer your question? [How to draw polygons with Python?](https://stackoverflow.com/questions/43971259/how-to-draw-polygons-with-python) – Christoph Rackwitz Jul 06 '23 at 19:50
  • https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill.html https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Polygon.html – Christoph Rackwitz Jul 06 '23 at 19:50

0 Answers0