Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Largest circle inside a contour - Python

I want to find the largest circle(or rectangle) possible inside the contours generated in this code. This is the binary image that the contours are generated from:

image description

I have this code:

import cv2
import numpy as np
import time
import math
from picamera.array import PiRGBArray
from picamera import PiCamera

#initialize the camera and grab a reference to the raw camera capture
#and set the resolution
camera=PiCamera()
rawCapture=PiRGBArray(camera)
camera.resolution=(800,608)

#allow the camera to sleep
time.sleep(0.1)

#grab an image
camera.capture(rawCapture, format="bgr")
image=rawCapture.array

#convert from BGR to HSV for easier segmentation
hsvimage=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)

#define the orange we want to filter out of the image
lower_orange=np.array([0,42,75])
upper_orange=np.array([40,203,220])

#Threshold the HSV image
imagebinary=cv2.inRange(hsvimage, lower_orange, upper_orange)

#Invert the HSV image
invbinimg=cv2.bitwise_not(imagebinary)

#apply findContours
modimg, contours, hierarchy=cv2.findContours(invbinimg,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)

#filter out the contours that doesn't have the correct area size and draw the into original image

area_min=3000
area_max=4000

#loop through the contours with certain conditions
for i in range(len(contours)):
    cnt=contours[i]
    area=cv2.contourArea(cnt)
    centres=[]

    #if area is the correct one
    if (area > area_min) and (area < area_max):
            moments=cv2.moments(contours[i])
            hu=cv2.HuMoments(moments)
            #Sort out the parts that are upside down with moments
            if (hu[6] < 0):
                #Calculate and draw center of mass
                centres.append((int(moments['m10']/moments['m00']),int(moments['m01']/moments['m00'])))
                cv2.circle(image, centres[-1],3,(0,0,255),-1)
                cv2.drawContours(image, contours, i, (0,255,0), 2)
                #THIS IS WHERE I NEED HELP, draw the largest circle(or rectangle) possible in the 
                #i-th contour
                #cv2.pointPolygonTest...

            #show coordinates of the centers of mass    
            print(centres)


#display image on screen and wait for a keypress
cv2.imshow("show", image)
#save imaginebinary
cv2.imwrite("/home/pi/springs/imagebinary.png", imagebinary)
cv2.waitKey(0)
cv2.destroyAllWindows()

This is the result I want How can I implement this in my code? As far as I've understood, pointPolygonTest should be a suiting function, but I have no clue how to use it in my for-loop. Please help!

image description