The problem: I have a binary image, with multiple objects. I need to find a way to fit the largest possible Square in these irregular objects. see image attached below
I tried to formulate this as an optimization problem using boundingbox of each labelled object as initial guess and a cost function as shown below. Bounding Box rows are assumed as initial guess for colums as well since its a square.
Using the same approach as Stefan's answer on stackoverflow: fitting a circle to a binary image For my parameters I cannot figure out how to optimize the parameters against this simple cost function
import scipy.optimize as optimize
import numpy as np
import skimage.draw as draw
import skimage.measure as measure
def cost(params):
baser,basec,deltar = params
ycords = range(int(baser),int(baser + deltar))
xcords = range(int(basec),int(basec + deltar))
coords = draw.polygon(ycords,xcords,shape=region.image.shape)
template = np.zeros_like(region.image)
template[coords] = 1
return -np.sum(template == region.image)
labels , nlabels = measure.label(img,neighbors=4,return_num=True)
regions = measure.regionprops(labels.astype(int))
for region in regions:
minr, minc, maxr, _ = region.bbox
baser = minr
basec = minc
deltar = maxr-minr # One parameter in case of square
print "intial :", baser,basec,deltar
OptimizeResult = optimize.fmin(cost,(baser,basec,deltar),disp=True)
baser,basec,deltar = OptimizeResult
print "final : " , OptimizeResult
# the above 2 are same. and so the results don't change
The params do not change, optimization stops at iteration 0. and cost does not change as well. I have tried different solvers, and optimize.minimize. the params don't change.
Ideally I would want a rectangle in each of the regions. each region(binary object) color coded in different color
Please also comment if optimization is a good way to solve these problems.
The Annotated image as requested is posted below.The rectangles(assume squares after edit) on a few objects are in BLACK (sorry for poor color choice)