【问题标题】:image dilation with python使用python进行图像膨胀
【发布时间】:2019-07-28 02:13:24
【问题描述】:

我正在尝试执行我在网上找到的一段代码,它给了我以下错误。 我是opencv的新手,所以请帮助我。 错误:

<ipython-input-1-7fe9c579ec14> in image_masking(filepath)
 15         gray = cv2.imread(filepath,0)
 16         edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
 ---> 17         edges = cv2.dilate(edges,None)
 18         edges = cv2.erode(edges, None)
 19 

 error: OpenCV(3.4.1) C:\Miniconda3\conda-bld\opencv- 
 suite_1533128839831\work\modules\core\src\matrix.cpp:760: error: (-215) 
 dims <= 2 && step[0] > 0 in function cv::Mat::locateROI

代码:

import cv2
import numpy as np

def image_masking(filepath):

    BLUR = 21
    CANNY_THRESH_1 = 100
    CANNY_THRESH_2 = 100
    MASK_DILATE_ITER = 10
    MASK_ERODE_ITER = 10
    MASK_COLOR = (0.0,0.0,0.0) # In BGR format

    gray = cv2.imread(filepath,0)
    edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
    edges = cv2.dilate(edges,None)
    edges = cv2.erode(edges, None)
    contour_info = []
    _, contours, __ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

    for c in contours:
        contour_info.append((c, cv2.isContourConvex(c), cv2.contourArea(c),))
     contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)

     max_contour = contour_info[0]
     for c in contour_info:
        cv2.fillConvexPoly(mask, c[0], (255))
     mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
     mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
     mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)

     mask_stack = np.dstack([mask]*3)
     mask_stack  = mask_stack.astype('float32') / 255.0
     img = img.astype('float32') / 255.0

     masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR)
     masked = (masked * 255).astype('uint8')

     fileName, fileExtension = filepath.split('.')
     fileName += '-masked.'
     filepath = fileName + fileExtension
     print(filepath)

     cv2.imwrite(filepath, masked)

if __name__ == '__main__':
    filepath = 'C:\\Users\HP\Downloads\test3.jpg'
    image_masking(filepath)

我尝试用内核替换扩张函数中的 None 但它给了我同样的错误

【问题讨论】:

  • 请复制粘贴错误(而不是屏幕截图)。另外,请添加完全可重现的代码。
  • 你为什么将 None 传递给 dilate 函数?
  • @api55 如果我将其更改为内核,它也会给我同样的错误。请帮助

标签: python-3.x opencv image-processing machine-learning


【解决方案1】:

cv2.dilatecv2.erode 的第二个参数应该是您想要执行膨胀/腐蚀的内核,如文档中所示:opencv documentation

例如,您可以尝试这样做:

kernel = np.ones((3, 3), np.uint8)
edges = cv2.dilate(edges, kernel)
edges = cv2.erode(edges, kernel)

祝你在进一步的 opencv 探索中好运!

【讨论】:

  • 如果我将其更改为内核,它也会给我同样的错误。请帮助
  • 你确定图片已经正确加载了吗?
  • 你能用 cv2.imshow('img', gray) 显示你的图像吗?
  • 是的,它有效,但仅适用于某些图像,我不明白为什么它不适用于每张图像
  • 也许这个答案对你有用stackoverflow.com/questions/24564889/…
猜你喜欢
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多