Extracting Contours from Image - Python

asked 2017-01-05 08:54:29 -0500

LDG gravatar image

Hi guys, I am new with OpenCV3.2 and I am trying to extract the contours of this image: image description

I am executing the following Python code but I can't manage the to extract the contours of the image,

import numpy as np
import cv2

im = cv2.imread('start.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
im, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(im,contours,-1,(255,0,0),2)

for h,cnt in enumerate(contours):
    mask = np.zeros(imgray.shape,np.uint8)
    cv2.drawContours(mask,[cnt],0,255,-1)
    mean = cv2.mean(im,mask = mask)

    x, y, w, h = cv2.boundingRect(cnt)
    print('X: ', x, 'Y: ', y, 'W: ', w, 'H: ', h)
    cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)

cv2.imshow('win', im)
cv2.waitKey(0) 
cv2.destroyAllWindows()

when I try to print the 4 coordinates x, y, w, z it prints out many rows, I think because is detecting all the rectangles in the image.

I am stuck here for a couple of hours now and I really can't find a solution.

Can anyone help me?

Thank you in advance

edit retag flag offensive close merge delete

Comments

Since it is a closed one, finding the largest contour will get you the box

ManuVISION gravatar imageManuVISION ( 2018-02-21 11:45:14 -0500 )edit