Displaying contours in OpenCV
Suppose you have used FindContours to find the outlines of things in an image, and now want to color each one a different color, perhaps in order to create a seed map for the watershed algorithm. This gets you an image with each area that FindContours found in a different color:
#Showing the contours. #contour_list is the output of cv.FindContours(), degapped is the image contours were found in contour_img = cv.CreateImage(cv.GetSize(degapped), IPL_DEPTH_8U, 3) contour = contour_list while contour.h_next() != None: color = get_rand_rgb(80,255) holecolor = get_rand_rgb(80,255) cv.DrawContours(contour_img, contour, color, holecolor, -1, CV_FILLED) contour = contour.h_next() show_img(contour_img, "contours " + str(iteration))
The real key here is iterating over the list of contours using h_next(), which took me longer than it should have to find.
The show_img() function is effectively just printf for OpenCV images, and looks like this:
def show_img(img, winName): #Debugging printf for images! cv.NamedWindow(winName) cv.ShowImage(winName, img) cv.WaitKey(0) cv.DestroyWindow(winName)
The function get_rand_rgb() gets a random RGB color with values for each color set to an integer in the range you pass it, like so:
def get_rand_rgb(min, max): return (random.randint(min,max),random.randint(min,max),random.randint(min,max))
I used 80,255 to get bright colors.
Recent Comments