用python进行图像扩张

时间:2019-03-06 12:01:03

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

我正在尝试执行在网上找到的一段代码,这给了我以下错误。 我是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,但这给了我同样的错误

1 个答案:

答案 0 :(得分:3)

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

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

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

祝您有更多的opencv探索机会!