建模竞赛题, 读入图像搜索边界, 重构三维模型
import Image
from numarray import array
from Gnuplot import Gnuplot
from math import ceil
imsize = (512, 512)
drt = (( 0, 1), ( 1, 1), ( 1, 0), ( 1, -1),
( 0, -1), ( -1, -1), ( -1, 0), ( -1, 1))
drt = array(drt)
def dofile(file, z):
im = Image.open(file)
a = im.getdata()
a = array(a).resize(*imsize)
r = list()
for i in xrange(imsize[0]):
for j in xrange(imsize[1]):
for dx, dy in drt:
if ( i+dx>=0 and i+dx < imsize[0] and
j+dy>=0 and j+dy < imsize[1] and
a[i][j] != a[i+dx][j+dy]):
r.append((i, j, z))
return r
def ddfile(file, z):
im = Image.open(file)
a = im.getdata()
a = array(a).resize(*imsize)
r = getedge(a, z)
return r
def getedge(a, z):
imsize = a.shape
r = list()
try:
for i in xrange(imsize[0]):
for j in xrange(imsize[1]):
if (a[i,j] == 0):
raise StopIteration
except StopIteration:
r.append((i,j, z))
if len(r)==0 :
return None
nd = 0
x, y = i, j
r.append((z, x, y))
while True:
for d in xrange(8):
dd = (nd+d) %8
if a[x+drt[dd][0], y + drt[dd][1]] == 0:
r.append((x, y, z))
x, y = (x, y) + drt[dd]
nd = (dd + 4 +1) %8
break
if x == i and y == j:
break
return r
def out(ofp):
np = 30
for i in xrange(100):
fname = 'abmp/'+str(i)+'.bmp'
r = ddfile(fname, i)
l = len(r)
step = (l-1.0)/np
for i in xrange(np):
x, y, z = r[int(step*i)]
ofp.write("%d/t%d/t%d/n"%(z, y, x))
x, y, z = r[0]
ofp.write("%d/t%d/t%d/n"%(z, y, x))
ofp.write("/n")
def pointplot():
g = Gnuplot()
g('set pm3d')
g('set hidden3d')
g('splot [0:500] [0:500] [0:500] "oo.dat" w l')
raw_input("Press Enter to continue...")
if __name__ == '__main__':
ofp = open('oo.dat', 'w')
out(ofp)
ofp.close()
pointplot()