如何在Python中使用drawContours OpenCV方法?

时间:2019-03-24 21:35:28

标签: python 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是黑色矩形的右上角。

1 个答案:

答案 0 :(得分:0)

我应该改用以下代码行(请参见the docs):

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