Ask Your Question
0

Problem in Drawing Contour

asked 2016-01-23 22:40:27 -0600

Dr Dre gravatar image

updated 2016-01-23 22:41:57 -0600

Hi guys I have written a simple code which draws the contour.

import numpy as np
import cv2
img = cv2.imread('New Bitmap Image.bmp')  
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   
ret,thresh = cv2.threshold(gray,129,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print len(contours)
cv2.drawContours(thresh,contours,-1,(0,255,0),3)

cv2.imshow('thresh1',thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

Instead of drwaing contour it gives a black screen . I dont know why this happens

I am using python 2.7 with cv2

Input image is

image description

edit retag flag offensive close merge delete

Comments

I tried drawing on the img it works . But if i try drawing for thresh it wont work.

This is happening for all the input images.

Dr Dre gravatar imageDr Dre ( 2016-01-23 22:43:55 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2016-01-24 01:08:02 -0600

berak gravatar image

updated 2016-01-24 02:03:53 -0600

cv.findContours() eats the image while finding the countours(see Note here).

if you need it later, please use a copy:

contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

then, since you want to draw something in color, you probably want to draw into img(which has 3 channels), not into thresh(which is binary, only 1 chan)

## your drawing is invisible, since you try to plot green
# cv2.drawContours(thresh,contours,-1,(0,255,0),3)
cv2.drawContours(img,contours,-1,(0,255,0),3)
edit flag offensive delete link more

Comments

When i replaced the code with above i got output image as

image link

But no contours were drawn on it

Dont understand why

Dr Dre gravatar imageDr Dre ( 2016-01-24 01:39:37 -0600 )edit

^^ please see edit:

berak gravatar imageberak ( 2016-01-24 02:02:36 -0600 )edit

So sir If I want to draw on the thresh how can i achieve this ???

Dr Dre gravatar imageDr Dre ( 2016-01-24 02:04:27 -0600 )edit
1

you can only use the 1st channel, b/w drawing, so:

cv2.drawContours(thresh,contours,-1,(128,0,0),3)
berak gravatar imageberak ( 2016-01-24 03:03:04 -0600 )edit
1

Thank U For the help berak

Dr Dre gravatar imageDr Dre ( 2016-01-24 03:44:17 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-01-23 22:40:27 -0600

Seen: 2,362 times

Last updated: Jan 24 '16