首页 > 解决方案 > 在现有图像上使用有界矩形绘制轮廓

问题描述

我的目标是拾取图像,分离出灰度阈值低于局部数字(例如 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'

关于我哪里出错的任何输入,以及编写上述代码的更好实践——我是一个初学者。

我希望这发生:

在此处输入图像描述

标签: pythonopencvimage-processing

解决方案


根据您使用的 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);

测试图像处理后的图像


推荐阅读