Search code examples
pythonimageopencvedge-detection

How to change the thickness of the edge (contour) of an Image?


I am trying to extract the edge of an image (its contour) and change its thickness. I want to give it like the stroke effect of Photoshop layer style. Photoshop stroke effect example: http://projectwoman.com/2012/11/smart-objects-and-strokes-in-photoshop.html

I was able to extract the edge from an image. Using canny edge or the pillow function.

1.using canny edge detection

img = cv2.imread(img_path,0)
edges = cv2.Canny(img,300,700)

2.using pillow filler

image = Image.open(img_path).convert('RGB')
image = image.filter(ImageFilter.FIND_EDGES())

but, I could not adjust the contour thickness.


Solution

  • Here a solution:

    import cv2
    import matplotlib
    import numpy as np
    import matplotlib.pyplot as plt
    
    image = cv2.imread('mickey.jpg')
    image = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)[...,0]
    
    def show_img(im, figsize=None, ax=None, alpha=None):
        if not ax: fig,ax = plt.subplots(figsize=figsize)
        ax.imshow(im, alpha=alpha)
        ax.set_axis_off()
        return ax
    
    def getBordered(image, width):
        bg = np.zeros(image.shape)
        _, contours, _ = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        biggest = 0
        bigcontour = None
        for contour in contours:
            area = cv2.contourArea(contour) 
            if area > biggest:
                biggest = area
                bigcontour = contour
        return cv2.drawContours(bg, [bigcontour], 0, (255, 255, 255), width).astype(bool) 
    
    im2 = getBordered(image, 10)
    
    show_img(im2, figsize=(10,10))
    

    enter image description here

    You can change thickness by changing param width in getBordered.