python - 在现有图像上使用有界矩形绘制轮廓
问题描述
我的目标是拾取图像,分离出灰度阈值低于局部数字(例如 3)的曲线/轮廓,然后在它们周围有矩形,同时将其写回原始图像 - 作为检测的一种方式灰度图像上的裂缝。以下是我想出的 - 通过在线查看教程。
# import the necessary packages
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('chest-ct-lungs.jpg',0)
ret,thresh = cv2.threshold(img,3,255,cv2.THRESH_BINARY_INV)
# Detect the contours in the image
image, contours =
cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
# Draw all the contours
all_contour_img = cv2.drawContours(image, contours, -1, (0,255,0), 3)
cv2.imwrite('all_contour_img.png',all_contour_img)
# Use bounding rectangles
x,y,w,h = cv2.boundingRect(contours)
cv2.rectangle(all_contour_img,(x,y),(x+w,y+h),(0,255,0),2)
# Draw over original image
imwrite(uint8(double(img)+all_contour_img), 'output.png');
但是,当我使用 python IDLE 运行它时,我得到了这个作为输出:
Traceback (most recent call last):
File "C:\Users\com\Desktop\python.py", line 17, in <module>
all_contour_img = cv2.drawContours(image, contours, -1, (0,255,0), 3)
TypeError: Expected cv::UMat for argument 'image'
关于我哪里出错的任何输入,以及编写上述代码的更好实践——我是一个初学者。
我希望这发生:
解决方案
根据您使用的 OpenCV 版本,cv2.findContours() 将返回轮廓列表和其他一些内容。您想要的只是轮廓列表。您可以忽略其他内容并通过将这些未使用的变量分配给_
.
cv2.findContours
返回轮廓列表。这就像一个形状列表。如果要bounding rectangle
在每个形状周围绘制一个,则需要遍历轮廓列表。
# Import the necessary packages
import numpy as np
import cv2
# Load an color image in grayscale, threshold
img = cv2.imread('/home/stephen/Desktop/test.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray,3,255,cv2.THRESH_BINARY_INV)
# Detect the contours in the image
_, contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
# Draw all the contours
img = cv2.drawContours(img, contours, -1, (0,255,0), 1)
# Iterate through all the contours
for contour in contours:
# Find bounding rectangles
x,y,w,h = cv2.boundingRect(contour)
# Draw the rectangle
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),1)
# Write the image
cv2.imwrite('/home/stephen/Desktop/lines.png', img);
推荐阅读
- material-ui - 有什么快速的方法来实现 Material-UI 主题吗?
- java - [android studio] handler.postdelayed 有问题
- python - Python Plotly:px.imshow 仅接受 2D 单通道、RGB 或 RGBA 图像。提供了形状 (5, 1440, 1920) 的图像
- algorithm - 在 Minecraft 中,找到玩家可以在不跳跃或跌倒的情况下行走的所有方块?
- php - Doctrine QueryBuilder 添加了取消 where 子句的 and 子句
- apache-spark - 写入 Synapse DWH 池时出现 Spark 错误
- python - 从文件创建数据框
- firebase - 为什么代码显示找不到模块?
- excel - 使用RUNAS启动应用程序时如何获取登录用户的用户名
- flutter - 如何使用颤振创建自定义弹出菜单与颤振代码相同