marshmallow
marshmallow

Reputation: 23

image dilation with python

I'm trying to execute a piece of code I found online and it is giving me the following error. I'm new to opencv so please help me. error:

<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

code:

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)

i tried replacing None in dilate function with kernel but it is giving me the same error

Upvotes: 1

Views: 2995

Answers (1)

melaanya
melaanya

Reputation: 314

The second argument to cv2.dilate and cv2.erode should be the kernel with which you want to perform dilation/erosion as it is shown in the docs: opencv documentation

For example, you can try to do it like that:

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

Good luck with further opencv exploration!

Upvotes: 3

Related Questions