#!/usr/bin/python
import Image,sys, numpy as np
def mk2d(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
tresh = lambda img,tr: img.point(lambda x: 255 if x>tr else 0)
def vsplit(img, t=1, smdrop=0, tr2=125):
i2=list(mk2d(list(img.getdata()), img.size[0]))
x,y=img.size
cols=[ [i2[r][c] for r in range(y)] for c in range(x)]
colcnt=[sum([1 if r>tr2 else 0 for r in c]) for c in cols]
xb=0
xe=0
ret=[]
print 'ffsd', len(colcnt), x
while xe<x-1:
while colcnt[xb]<t and xb <x: xb+=1
xe=xb
while colcnt[xe]>=t and xe<x-1: xe+=1
if xe-xb>smdrop: #found
ret.append(img.crop((xb,0,xe,y)))
ret[-1].load()
ret[-1]=ret[-1].copy() #dla pewnosci
print xb,xe
xb=xe
return ret
#nieuzywane
def otsu2(img):
hist = np.array(img.histogram())
hist = hist.astype(np.double)
Ng = len(hist)
nB = np.cumsum(hist)
nO = nB[-1]-nB
mu_B = 0
mu_O = (np.arange(1, Ng)*hist[1:]).sum()/hist[1:].sum()
best = nB[0]*nO[0]*(mu_B-mu_O)*(mu_B-mu_O)
bestT = 0
for T in xrange(1, Ng):
if nB[T] == 0: continue
if nO[T] == 0: break
mu_B = (mu_B*nB[T-1] + T*hist[T]) / nB[T]
mu_O = (mu_O*nO[T-1] - T*hist[T]) / nO[T]
sigma_between = nB[T]*nO[T]*(mu_B-mu_O)*(mu_B-mu_O)
if sigma_between > best:
best = sigma_between
bestT = T
return bestT
def main(argv):
i=Image.open(argv[1])
prefix=""
if len(argv) <3: prefix=""
else: prefix=argv[2]
s1=tresh(i.convert('L'),170).convert('1')
l2=vsplit(s1, 1)
if len(l2) < 4:
print "ERR"
return 2
for i in range(4):
l2[i].save(prefix+str(i)+'.png')
if __name__ == '__main__':
main(sys.argv)