Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Contour Numbering Doubt

Hi Guys

I Have an image as shown

image description

This is a simple code to create contour around the rectangular boxes.

import numpy as np
import cv2
img = cv2.imread('Image.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,100,255,cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,contours,-1,(0,255,0),3)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

When I write

cv2.drawContours(img,contours,0,(0,255,0),3)

I want contour to be drawn around black box

When I write

cv2.drawContours(img,contours,1,(0,255,0),3)

I want contour to be drawn around orange box

When I write

cv2.drawContours(img,contours,2,(0,255,0),3)

I want contour to be drawn around green box

and so on...............

But this doesn't happen . The system assigns contour number randomly as a result it is very difficult for me to get a particular contour that i want.

Why is the system numbering the contours randomly? Is there any concept about contouring that i have got wrong and is there any workaround so that i can get my contouring in the image in the manner as I discussed above.

I am using python and cv2