python - 如何在 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
解决方案
我应该改用这行代码(请参阅文档):
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
推荐阅读
- json - 从 JSON 文件填充 mat-select 选项
- sql - BigQuery SQL:在滚动时间窗口内执行查询
- memory - 操作系统三件容易——翻译栈内存地址
- git - 有没有办法将提交与家庭和公司区分开来?
- html - 如何在 CSS 网格布局中保持内容居中?
- mysql - 使用 vue.js 从数据库中删除产品
- java - Hibernate 不会自动创建表
- svelte - 来自父组件的样式槽元素
- python - Django 模型的表不包含给定的字段
- javascript - Razor 中的 JavaScript 断点在 Visual Studio 2019 中不起作用