Ask Your Question

How do i crop a contourn?

asked 2019-02-09 17:43:30 -0500

idervas gravatar image

updated 2019-02-10 07:44:38 -0500

berak gravatar image

Hello. I'm trying to write a code that identifies the eyes of parakeets. Currently, i'm using a code that identifies circles within a certain threshold and it is working great. The problem: I need the result image colored. I tried using masks to crop the contourn on the clone img with no luck. Any ideas on what i can do?

Those are the result images:

This is the original image:

image description

This is the kind of result that i want

import cv2
import numpy as np
import imutils

def nothing(x):

# Load an image
img = cv2.imread('papagaio.png')

# Resize The image
if img.shape[1] > 600:
img = imutils.resize(img, width=600)

# Create a window

# create trackbars for treshold change


# Clone original image to not overlap drawings
clone = img.copy()

# Convert to gray
gray = cv2.cvtColor(clone, cv2.COLOR_BGR2GRAY)

# get current positions of four trackbars
r = cv2.getTrackbarPos('Treshold','Treshed')

# Thresholding the gray image
ret,gray_threshed = cv2.threshold(gray,r,255,cv2.THRESH_BINARY)

# Blur an image
bilateral_filtered_image = cv2.bilateralFilter(gray_threshed, 5, 175, 175)

# Detect edges
edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)

# Find contours
contours, _= cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    # approximte for circles
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) > 8) & (area > 30) ):

# Draw contours on the original image
cv2.drawContours(clone, contour_list,  -1, (255,0,0), 2)

# there is an outer boundary and inner boundary for each eadge, so contours double
print('Number of found circles: {}'.format(int(len(contour_list)/2)))

#Displaying the results     
cv2.imshow('Objects Detected', clone)
cv2.imshow("Treshed", gray_threshed)

# ESC to break
k = cv2.waitKey(1) & 0xFF
if k == 27:

# close all open windows
edit retag flag offensive close merge delete


could you post the original image (papagaio.png) here

sturkmen gravatar imagesturkmen ( 2019-02-09 18:11:22 -0500 )edit

Already did!

idervas gravatar imageidervas ( 2019-02-09 18:21:36 -0500 )edit

Sorry I don't understand what you want. Can you give result image (handly make) ?

LBerger gravatar imageLBerger ( 2019-02-10 03:25:31 -0500 )edit

Updated the post with a example of what i want. Thank you for your attention!

idervas gravatar imageidervas ( 2019-02-10 06:19:10 -0500 )edit

@idervas, you already have a loop there, that evaluates the contourArea.

find the contour with the largest area, then crop using cv2.getBoundingRect(largest_contour)

berak gravatar imageberak ( 2019-02-10 06:23:29 -0500 )edit

I'm sorry, but i don't know how to find the contour with the largest area.

idervas gravatar imageidervas ( 2019-02-10 07:37:44 -0500 )edit

@dervas, try harder !

(you really need minimal coding skills here, and can't always rely on th e kindness of strangers)

berak gravatar imageberak ( 2019-02-10 07:41:40 -0500 )edit

@berak thank you for you feedback. I already managed the problem by using a filled contourn, cropping and masks. I know fully well that i need to study more and i'm more than willing to do so! I've only solved the problem by repeating things that i saw other people doing on the internet, but maybe someday i can come with my own resolutions for my problems. Thank you again.

idervas gravatar imageidervas ( 2019-02-10 11:35:59 -0500 )edit

@idervas with your code evreythinkg is wrote in your code : fill largest circle and that's your mask image

LBerger gravatar imageLBerger ( 2019-02-10 11:44:57 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2019-02-13 06:47:36 -0500

supra56 gravatar image

Here is code :

import cv2
import numpy as np

img = cv2.imread('papagaio.png')
output = img.copy()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,4,10000,param1=100,param2=4,minRadius=4,maxRadius=70)

if circles is not None:
    circles = np.round(circles[0,:]).astype("int")
    if len(circles) == 1:
        x,y,r = circles[0] 
        mask = np.zeros((img.shape[1],img.shape[0],3),np.uint8),(x,y),r,(255,255,255),-1,8,0)
        out = img*mask
        white = 255-mask
        cv2.imshow('cing', out)


Output: image description image description

Go back your orginal code that posted before. circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,4,10000,param1=100,param2=4,minRadius=4,maxRadius=70)

Output: image description

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2019-02-09 17:43:30 -0500

Seen: 55 times

Last updated: Feb 13