# 情报理工海报的图像处理

Posted on November 6, 2012 on python

from PIL import Image

im = Image.open('poster.jpg')

for y in xrange(im.size[1]):
for x in xrange(im.size[0]):
a, b, c = pix[x, y]
m = (a + b + c) / 3
if 140 < m < 170:
avg = sum(map(abs, (a - m, b - m, c - m)))
if   avg < 50:
pix[x, y] = (0, 0, 0)
elif avg < 70:
pix[x, y] = (50, 50, 50)
elif avg < 90:
pix[x, y] = (150, 150, 150)
else:
pix[x, y] = (255, 255, 255)
else:
if 80 < a < 150 and 70 < b < 140 and 70 < c < 140:
pix[x, y] = (0, 0, 255)
else:
pix[x, y] = (255, 255, 255)

im.show()
im.save('p.png', 'png')

1000111011100100110000101100100011101010

# coding: utf-8
from PIL import Image

im = Image.open('test.png')
im = im.convert('L')  # 转灰度
size = list(im.size)

# 获得7*5的区域的灰度矩阵
def get(pix, sx, sy):
d = [[0 for i in xrange(7)] for j in xrange(5)]
for y in xrange(7):
for x in xrange(5):
d[x][y] = pix[sx + x, sy + y]
return d

# 前两个作为0,1标准
d1 = get(pix, 0, 0)
d0 = get(pix, 5, 0)

# 灰度矩阵和标准间比对打分
def score(da, db):
sc = 0
for y in xrange(7):
for x in xrange(5):
sc += abs(da[x][y] - db[x][y])
return sc

# 根据打分猜0或1
def guess(pix, sx, sy):
d = get(pix, sx, sy)
s = (score(d, d0), score(d, d1))
if s[0] < s[1]:
return 0, min(s[0], s[1])
else:
return 1, min(s[0], s[1])

x = 0
while x < size[0] - 4:
g, s = guess(pix, x, 0)
if x > 0:  # 测试左抖动 1px
gl, sl = guess(pix, x - 1, 0)
if sl < s - 1000:
#print 'l',s,sl
g, s, x = gl, sl, x - 1
if x < size[0] - 5:  # 测试右抖动 1px
gr, sr = guess(pix, x + 1, 0)
if sr < s - 1000:
#print 'r',s,sr
g, s, x = gr, sr, x + 1
#print 'x:',x, s, g
print g,
x += 5