user4584333
user4584333

Reputation:

draw contour with cv2.threshold() function

I am testing the cv2.threshold() function in with different values but I get each time unexpected results. So this means simply I do not understand the effect of the parameter:

Could someone clear me on this ?

For example, I want to draw the contours of this star following the white color:

enter image description here

Here is what I got:

enter image description here

From this code:

import cv2    
im=cv2.imread('image.jpg') # read picture

imgray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # BGR to grayscale

ret,thresh=cv2.threshold(imgray,200,255,cv2.THRESH_BINARY_INV)

countours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)


cv2.drawContours(im,countours,-1,(0,255,0),3)
cv2.imshow("Contour",im)

cv2.waitKey(0)
cv2.destroyAllWindows()

Each time I change the value of maxval I get a strange result that I can not understand. How can I draw the contour of this star correctly using this function then ?

Thank you in advance.

Upvotes: 1

Views: 14964

Answers (3)

Asfandyar Saeed
Asfandyar Saeed

Reputation: 11

well here you can use COLOR_BGR2HSV and then choose a color and the making of contour will be quite easy try it and let me know in black and while conversion u have same color of yellow and white thats why this is not working

Upvotes: 1

blitu12345
blitu12345

Reputation: 3567

For better accuracy at finding contours one may apply threshold on image as binary image tend to give higher accuracy and then use contours method.Hope this will help..!!!

Upvotes: 0

Satya Mallick
Satya Mallick

Reputation: 2927

You may want to experiment with a very simple image that clearly lets you understand the various parameters. The interesting thing about the image attached below is that the grayscale value of a number shown in the image is equal to the number. E.g. 200 is written with grayscale value 200. Here is example python code you can use.

import cv2

# Read image
src = cv2.imread("threshold.png", cv2.CV_LOAD_IMAGE_GRAYSCALE)

# Set threshold and maxValue
thresh = 127
maxValue = 255

# Basic threshold example
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY);

# Find Contours 
countours,hierarchy=cv2.findContours(dst,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Draw Contour
cv2.drawContours(dst,countours,-1,(255,255,255),3)

cv2.imshow("Contour",dst)
cv2.waitKey(0)

I have copied the following image from a OpenCV Threshold Tutorial I wrote recently. It explains the various parameters with example image, Python and C++ Code. Hope this helps.

Input Image

OpenCV Threshold Test Image

Result Imageenter image description here

Upvotes: 6

Related Questions