在现有图像上绘制带有边界矩形的轮廓

时间:2019-03-26 16:58:10

标签: python opencv image-processing

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

关于我要去哪里的任何信息,以及编写上述代码的更好做法-我是初学者。

我希望这种情况发生:

enter image description here

1 个答案:

答案 0 :(得分:2)

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

test image processed image