首页 > 解决方案 > 如何在 Python 中使用 drawContours OpenCV 方法?

问题描述

我有以下代码:

import cv2

img = cv2.imread('image.png')

# Convert image to grayscale image
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Convert the grayscale image to binary image
_, threshold = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
print(threshold)
# [[255 255 255 ... 255 255 255]
#  [255 255 255 ... 255 255 255]
#  [255 255 255 ... 255 255 255]
#  ...
#  [  0   0   0 ...   0   0   0]
#  [  0   0   0 ...   0   0   0]
#  [  0   0   0 ...   0   0   0]]
_, contours = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(contours)
# [[[-1 -1 -1 -1]]]

为什么我会收到如此奇怪的轮廓输出?我图像的下半部分是黑色的,上半部分是白色的。我希望看到左下角contours = [[height, 0, width, height / 2]]在哪里,是黑色矩形的右上角。(height, 0)(width, height / 2)image.png

标签: pythonopencv

解决方案


我应该改用这行代码(请参阅文档):

contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

推荐阅读