ved*_*ala 1 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');
Run Code Online (Sandbox Code Playgroud)
但是,当我使用 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'
Run Code Online (Sandbox Code Playgroud)
关于我哪里出错的任何输入,以及编写上述代码的更好做法 - 我是初学者。
我希望这发生:
根据您使用的 OpenCV 版本, cv2.findContours() 将返回轮廓列表和其他一些内容。您想要的只是轮廓列表。您可以忽略其他内容并通过将那些未使用的变量分配给_
.
cv2.findContours
返回轮廓列表。这就像一个形状列表。如果要bounding rectangle
围绕每个形状绘制 a ,则需要遍历轮廓列表。
# 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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2595 次 |
最近记录: |