def removeDarkAreas img wrk np copy img areas cv2 findContours wrk cv2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def removeDarkAreas(img):
wrk = np.copy(img)
areas, _ = cv2.findContours(wrk, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
rects = [ cv2.boundingRect(c) for c in areas ]
avgs=[]
for r in rects:
region = img[r[1]:r[1]+r[3],r[0]:r[0]+r[2]]
avgs.append(np.average(region[region > 0]))
goodRects = [ avgs[i] for i in range(len(rects)) if rects[i][2] <= 15 and rects[i][3] <= 15 and rects[i][3] > 6]
avg = np.average(goodRects)
stddev = np.std(goodRects)
print avg, stddev
for i in range(len(rects)):
r = rects[i]
if r[2] > 30 or r[3] > 30 or r[3] == 1 or r[2]*r[3] < 8 or abs(avgs[i] - avg) > stddev * 5:
img[r[1]:r[1]+r[3],r[0]:r[0]+r[2]] = 0