Below is my identify background code, which identifies a background from an image and removes it.;
Previously it's was working fine but after I chunked my images and try to find out background I got an error.
Traceback (most recent call last):
File "create_vips_test.py", line 336, in
print test_h5_file()
File "create_vips_test.py", line 243, in test_h5_file
res = identify_background(tile).astype(np.int16)
File "create_vips_test.py", line 111, in identify_background
max_area=np.max([cv2.contourArea(cnt) for cnt in contour])
File "/usr/local/lib/python2.7/site-packages/numpy/core/fromnumeric.py",
line 2293, in amax out=out, **kwargs)
File "/usr/local/lib/python2.7/site-packages/numpy/core/_methods.py",
line 26, in _amax return umr_maximum(a, axis, None, out, keepdims)
ValueError: zero-size array to reduction operation maximum which has no identity
def identify_background(img):
im = cv2.cvtColor(np.array(img), cv2.COLOR_RGBA2GRAY)
# print 'identiyf background ', im
blur = cv2.GaussianBlur(im,(5,5),0)
# print 'blur', blur
# find normalized_histogram, and its cumulative distribution function
hist = cv2.calcHist([blur],[0],None,[256],[0,256])
hist_norm = hist.ravel()/hist.max()
Q = hist_norm.cumsum()
bins = np.arange(256)
# print 'bins', bins
fn_min = np.inf
thresh = -1
for i in xrange(1,256):
p1,p2 = np.hsplit(hist_norm,[i]) # probabilities
q1,q2 = Q[i],Q[255]-Q[i] # cum sum of classes
b1,b2 = np.hsplit(bins,[i]) # weights
# finding means and variances
m1,m2 = np.sum(p1*b1)/q1, np.sum(p2*b2)/q2
v1,v2 = np.sum(((b1-m1)**2)*p1)/q1,np.sum(((b2-m2)**2)*p2)/q2
# calculates the minimization function
fn = v1*q1 + v2*q2
if fn < fn_min:
fn_min = fn
thresh = i
# find otsu's threshold value with OpenCV function
ret, otsu = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# print 'ret', ret
# print 'otsu',otsu
orig=otsu
final=cv2.bitwise_and(orig, cv2.bitwise_not(orig))
# print 'final', final
im_bw_inv = cv2.bitwise_not(orig)
# print 'im_bw_inv', im_bw_inv
contour, _ = cv2.findContours(im_bw_inv, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# print 'contour, _', len(contour), _
max_area=np.max([cv2.contourArea(cnt) for cnt in contour])
# print 'contour', contour
# print 'max area', max_area
for cnt in contour:
cv2.drawContours(final, [cnt], 0, 255, -1)
# print 'final', final
return final