tes*_*tes 0 python opencv functional-programming filter
我想过滤掉面积较小的碳纳米管。但我得到了一个错误。过滤器的正确使用方法是什么?
代码
def drawCnts(img, cnts):
cnts = filter(lambda cnt: cv2.contourArea(cnt)> 400, cnts) # adding this line gets error
cv2.drawContours(img, cnts, -1, (0, 255, 0), 3)
imshow(img)
Run Code Online (Sandbox Code Playgroud)
import imUtils
import configure as cfg
import cv2
folder = 'test_images/'
img = imUtils.imread(folder + '1.cr3')
gray = cv2.cvtColor(imUtils.toOpenCVU8(img.copy()), cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,27,9)
# apply close morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
imUtils.imshow(thresh, 'thresh')
(cnts, _) = cv2.findContours(thresh.copy(),
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
imUtils.drawCnts(img.copy(), cnts)
Run Code Online (Sandbox Code Playgroud)
错误
import imUtils
import configure as cfg
import cv2
folder = 'test_images/'
img = imUtils.imread(folder + '1.cr3')
gray = cv2.cvtColor(imUtils.toOpenCVU8(img.copy()), cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,27,9)
# apply close morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
imUtils.imshow(thresh, 'thresh')
(cnts, _) = cv2.findContours(thresh.copy(),
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
imUtils.drawCnts(img.copy(), cnts)
Run Code Online (Sandbox Code Playgroud)
filter 函数返回一个生成器,但 drawContours 函数需要一个列表。要解决此问题,请使用 list 命令。
cnts = list(filter(lambda cnt: cv2.contourArea(cnt)> 400, cnts))
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是使用列表理解来构建列表,如下所示:
[cnt for cnt in cnts if cv2.contourArea(cnt) > 400]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |